import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'device_storage_service.dart';
import 'device_sn_manager.dart';
import '../common/utils/device_utils.dart';
import '../core/repository/default_api.dart';
import '../core/models/ring_sport_record.dart';
import '../core/models/ring_sport_detail.dart';
import '../core/models/sleep_detail.dart';
import '../core/utils/history_day_helper.dart';
import 'package:flutter/material.dart';
import '../pages/status/status_logic.dart';
import '../pages/sleep/sleep_logic.dart';

/// 戒指设备信息模型
class RingDevice {
  final String name;
  final String address;
  final int rssi;
  final String? scanRecord;
  final String deviceSn; // 设备序列号，优先使用chipId，fallback到地址
  final bool isCharging; // 是否正在充电

  RingDevice({
    required this.name,
    required this.address,
    required this.rssi,
    this.scanRecord,
    this.isCharging = false,
  }) : deviceSn = _generateDeviceSn(address);

  /// 生成设备序列号
  static String _generateDeviceSn(String address) {
    return DeviceUtils.convertAddressToDeviceSn(address);
  }

  factory RingDevice.fromMap(Map<String, dynamic> map) {
    // 解析 scanRecord 中的 visable 字段
    bool isCharging = false;
    final scanRecord = map['scanRecord'];
    if (scanRecord != null && scanRecord is String) {
      final match = RegExp(r'visable=(\w+)').firstMatch(scanRecord);
      if (match != null) {
        isCharging = match.group(1)?.toLowerCase() == 'true';
      }
    }

    return RingDevice(
      name: map['name'] ?? '未知设备',
      address: map['address'] ?? '',
      rssi: map['rssi'] ?? 0,
      scanRecord: scanRecord,
      isCharging: isCharging,
    );
  }

  /// 获取芯片ID（如果可用）
  String? get chipId {
    if (scanRecord != null) {
      final match = RegExp(r'chipId=(\d+)').firstMatch(scanRecord!);
      return match?.group(1);
    }
    return null;
  }

  /// 获取固件类型（如果可用）
  String? get firmwareType {
    if (scanRecord != null) {
      final match = RegExp(r"firmwareType='([^']+)'").firstMatch(scanRecord!);
      return match?.group(1);
    }
    return null;
  }

  /// 获取设备颜色（如果可用）
  String? get deviceColor {
    if (scanRecord != null) {
      final match = RegExp(r'color=(\d+)').firstMatch(scanRecord!);
      return match?.group(1);
    }
    return null;
  }

  /// 获取设备尺寸（如果可用）
  String? get deviceSize {
    if (scanRecord != null) {
      final match = RegExp(r'size=(\d+)').firstMatch(scanRecord!);
      return match?.group(1);
    }
    return null;
  }

  @override
  String toString() {
    return 'RingDevice(name: $name, address: $address, deviceSn: $deviceSn, chipId: $chipId, rssi: $rssi)';
  }
}

/// 步数数据模型
/// 注意：distance 和 calories 是 SDK 原始值，需要转换：
/// - distance: SDK 返回厘米，需要除以 100 得到米
/// - calories: SDK 返回 0.0001 卡路里，需要除以 10000 得到卡路里
class StepsData {
  final int steps;
  final int distance; // SDK 原始值（厘米）
  final int calories; // SDK 原始值（0.0001 卡路里）
  final int? time; // 时长字段可能为空（分钟）
  final List<int?>? hourlySteps; // 每半小时的步数数据

  const StepsData({
    required this.steps,
    required this.distance,
    required this.calories,
    this.time,
    this.hourlySteps,
  });

  factory StepsData.fromMap(Map<String, dynamic> map) {
    List<int?>? hourlyData;
    if (map['stepsList'] != null) {
      // 保留null值，使用List<int?>
      final rawList = map['stepsList'] as List?;
      if (rawList != null) {
        hourlyData = rawList.map((item) => item as int?).toList();
      }
    }

    return StepsData(
      steps: map['steps'] ?? 0,
      distance: map['distance'] ?? 0,
      calories: map['calories'] ?? 0,
      time: map['time'], // 允许为null
      hourlySteps: hourlyData,
    );
  }

  @override
  String toString() {
    return 'StepsData(steps: $steps, distance: $distance, calories: $calories, time: $time, hourlySteps: ${hourlySteps?.length ?? 0} entries)';
  }
}

/// 睡眠数据模型
class SleepData {
  final int totalSleepTime; // 总睡眠时间（分钟）
  final int deepSleepTime; // 深睡眠时间（分钟）
  final int lightSleepTime; // 浅睡眠时间（分钟）
  final int remSleepTime; // REM睡眠时间（分钟）
  final int awakeTime; // 清醒时间（分钟）
  final int awakeTimes; // 醒来次数
  final String? historyDay; // 历史日期
  final List<SleepStageDetail>? details; // 详细睡眠阶段数据
  final double? sleepEfficiency; // 睡眠效率
  final double? score; // 睡眠评分
  final DateTime? startDate; // 睡眠开始时间
  final DateTime? endDate; // 睡眠结束时间
  final String? sleepType; // 睡眠类型
  final String? chronotype; // 睡眠类型（早鸟/夜猫子等）

  SleepData({
    required this.totalSleepTime,
    required this.deepSleepTime,
    required this.lightSleepTime,
    required this.remSleepTime,
    required this.awakeTime,
    required this.awakeTimes,
    this.historyDay,
    this.details,
    this.sleepEfficiency,
    this.score,
    this.startDate,
    this.endDate,
    this.sleepType,
    this.chronotype,
  });

  /// 从Map创建SleepData对象
  factory SleepData.fromMap(Map<String, dynamic> map) {
    // 处理新的数据结构，包含完整的info对象
    if (map.containsKey('info') && map['info'] is Map) {
      final infoMap = map['info'] as Map<String, dynamic>;
      return SleepData(
        totalSleepTime: infoMap['totalTime'] ?? 0,
        deepSleepTime: infoMap['deepTime'] ?? 0,
        lightSleepTime: infoMap['lightTime'] ?? 0,
        remSleepTime: infoMap['remTime'] ?? 0,
        awakeTime: infoMap['awakeTime'] ?? 0,
        awakeTimes: 0, // 需要从details中计算
        historyDay: map['historyDay'],
        details: _parseSleepDetails(infoMap['details']),
        sleepEfficiency: infoMap['sleepEfficiency']?.toDouble(),
        score: infoMap['score']?.toDouble(),
        startDate: _parseDateTime(infoMap['startDate']),
        endDate: _parseDateTime(infoMap['endDate']),
        sleepType: infoMap['type'],
        chronotype: infoMap['chronotype'],
      );
    }

    // 兼容旧的数据结构
    return SleepData(
      totalSleepTime: map['totalSleepTime'] ?? 0,
      deepSleepTime: map['deepSleepTime'] ?? 0,
      lightSleepTime: map['lightSleepTime'] ?? 0,
      remSleepTime: map['remSleepTime'] ?? 0,
      awakeTime: map['awakeTime'] ?? 0,
      awakeTimes: map['awakeTimes'] ?? 0,
      historyDay: map['historyDay'],
      details: _parseSleepDetails(map['details']),
      sleepEfficiency: map['sleepEfficiency']?.toDouble(),
      score: map['score']?.toDouble(),
      startDate: _parseDateTime(map['startDate']),
      endDate: _parseDateTime(map['endDate']),
      sleepType: map['type'],
      chronotype: map['chronotype'],
    );
  }

  /// 解析睡眠详细阶段数据
  static List<SleepStageDetail>? _parseSleepDetails(dynamic detailsData) {
    if (detailsData == null || detailsData is! List) return null;

    return detailsData
        .map((detail) {
          if (detail is Map<String, dynamic>) {
            return SleepStageDetail(
              startTime: detail['startTime'] ?? 0,
              endTime: detail['endTime'] ?? 0,
              totalTime: detail['totalTime'] ?? 0,
              type: detail['type'] ?? 0,
            );
          }
          return null;
        })
        .whereType<SleepStageDetail>()
        .toList();
  }

  /// 解析日期时间
  static DateTime? _parseDateTime(dynamic dateData) {
    if (dateData == null) return null;
    if (dateData is String) {
      try {
        return DateTime.parse(dateData);
      } catch (e) {
        print('解析日期失败: $dateData, 错误: $e');
        return null;
      }
    }
    return null;
  }

  /// 计算睡眠质量评分
  int get qualityScore {
    if (totalSleepTime == 0) return 0;

    // 基础分数：睡眠时长评分（0-40分）
    int durationScore = 0;
    if (totalSleepTime >= 420 && totalSleepTime <= 540) {
      // 7-9小时
      durationScore = 40;
    } else if (totalSleepTime >= 360 && totalSleepTime < 420) {
      // 6-7小时
      durationScore = 30;
    } else if (totalSleepTime >= 300 && totalSleepTime < 360) {
      // 5-6小时
      durationScore = 20;
    } else if (totalSleepTime >= 240 && totalSleepTime < 300) {
      // 4-5小时
      durationScore = 10;
    }

    // 睡眠效率评分（0-30分）
    int efficiencyScore = 0;
    if (sleepEfficiency != null) {
      if (sleepEfficiency! >= 0.9) {
        efficiencyScore = 30;
      } else if (sleepEfficiency! >= 0.8) {
        efficiencyScore = 25;
      } else if (sleepEfficiency! >= 0.7) {
        efficiencyScore = 20;
      } else if (sleepEfficiency! >= 0.6) {
        efficiencyScore = 15;
      } else {
        efficiencyScore = 10;
      }
    }

    // 深睡眠比例评分（0-20分）
    int deepSleepScore = 0;
    if (totalSleepTime > 0) {
      double deepSleepRatio = deepSleepTime / totalSleepTime;
      if (deepSleepRatio >= 0.2 && deepSleepRatio <= 0.25) {
        deepSleepScore = 20;
      } else if (deepSleepRatio >= 0.15 && deepSleepRatio < 0.2) {
        deepSleepScore = 15;
      } else if (deepSleepRatio >= 0.1 && deepSleepRatio < 0.15) {
        deepSleepScore = 10;
      } else {
        deepSleepScore = 5;
      }
    }

    // 醒来次数扣分（0-10分）
    int awakePenalty = 0;
    if (awakeTimes > 0) {
      if (awakeTimes <= 2) {
        awakePenalty = 0;
      } else if (awakeTimes <= 4) {
        awakePenalty = 5;
      } else {
        awakePenalty = 10;
      }
    }

    int totalScore =
        durationScore + efficiencyScore + deepSleepScore - awakePenalty;
    return totalScore.clamp(0, 100);
  }

  /// 睡眠质量描述
  String get qualityDescription {
    final score = qualityScore;
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '一般';
    if (score >= 60) return '较差';
    return '很差';
  }

  /// 睡眠质量颜色
  Color get qualityColor {
    final score = qualityScore;
    if (score >= 80) return Colors.green;
    if (score >= 60) return Colors.orange;
    return Colors.red;
  }

  /// 睡眠时长显示
  String get sleepDurationDisplay {
    if (totalSleepTime == 0) return '--';
    final hours = totalSleepTime ~/ 60;
    final minutes = totalSleepTime % 60;
    return '${hours}小时${minutes}分';
  }

  /// 睡眠时间范围显示
  String get sleepTimeRange {
    if (startDate == null || endDate == null) return '--';

    final startHour = startDate!.hour.toString().padLeft(2, '0');
    final startMinute = startDate!.minute.toString().padLeft(2, '0');
    final endHour = endDate!.hour.toString().padLeft(2, '0');
    final endMinute = endDate!.minute.toString().padLeft(2, '0');

    return '$startHour:$startMinute - $endHour:$endMinute';
  }

  /// 获取睡眠阶段统计
  Map<String, int> get sleepStageStats {
    return {
      'deep': deepSleepTime,
      'light': lightSleepTime,
      'rem': remSleepTime,
      'awake': awakeTime,
    };
  }

  /// 获取睡眠阶段百分比
  Map<String, double> get sleepStagePercentages {
    if (totalSleepTime == 0) {
      return {'deep': 0.0, 'light': 0.0, 'rem': 0.0, 'awake': 0.0};
    }

    return {
      'deep': (deepSleepTime / totalSleepTime * 100).roundToDouble(),
      'light': (lightSleepTime / totalSleepTime * 100).roundToDouble(),
      'rem': (remSleepTime / totalSleepTime * 100).roundToDouble(),
      'awake': (awakeTime / totalSleepTime * 100).roundToDouble(),
    };
  }

  @override
  String toString() {
    return 'SleepData{totalSleepTime: $totalSleepTime, deepSleepTime: $deepSleepTime, lightSleepTime: $lightSleepTime, remSleepTime: $remSleepTime, awakeTime: $awakeTime, awakeTimes: $awakeTimes, qualityScore: $qualityScore}';
  }
}

/// 睡眠阶段详细数据（用于UI显示）
class SleepStageDetail {
  final int startTime; // 开始时间（分钟）
  final int endTime; // 结束时间（分钟）
  final int totalTime; // 持续时间（分钟）
  final int type; // 睡眠类型：0=清醒, 1=浅睡眠, 2=深睡眠, 3=REM睡眠

  SleepStageDetail({
    required this.startTime,
    required this.endTime,
    required this.totalTime,
    required this.type,
  });

  /// 获取睡眠类型描述
  String get typeDescription {
    switch (type) {
      case 0:
        return '清醒';
      case 1:
        return '浅睡眠';
      case 2:
        return '深睡眠';
      case 3:
        return 'REM睡眠';
      default:
        return '未知';
    }
  }

  /// 获取睡眠类型颜色
  Color get typeColor {
    switch (type) {
      case 0:
        return Colors.red;
      case 1:
        return Colors.blue;
      case 2:
        return Colors.purple;
      case 3:
        return Colors.green;
      default:
        return Colors.grey;
    }
  }

  @override
  String toString() {
    return 'SleepStageDetail{startTime: $startTime, endTime: $endTime, totalTime: $totalTime, type: $type}';
  }
}

/// 血氧数据模型
class BloodOxygenData {
  final int bloodOxygen;
  final DateTime timestamp;

  const BloodOxygenData({
    required this.bloodOxygen,
    required this.timestamp,
  });

  factory BloodOxygenData.fromMap(Map<String, dynamic> map) {
    return BloodOxygenData(
      bloodOxygen: map['bloodOxygen'] ?? 0,
      timestamp: DateTime.now(),
    );
  }

  /// 获取血氧状态
  String get status {
    if (bloodOxygen >= 95) return '正常';
    if (bloodOxygen >= 90) return '较低';
    return '偏低';
  }

  @override
  String toString() {
    return 'BloodOxygenData(bloodOxygen: $bloodOxygen%, timestamp: $timestamp)';
  }
}

/// 血氧历史数据模型
class HistoryBloodOxygenData {
  final int startTime;
  final List<int?> bloodOxygenList; // 保留null值
  final int timeInterval;
  final String historyDay;

  const HistoryBloodOxygenData({
    required this.startTime,
    required this.bloodOxygenList,
    required this.timeInterval,
    required this.historyDay,
  });

  factory HistoryBloodOxygenData.fromMap(Map<String, dynamic> map) {
    List<int?> bloodOxygenData = [];
    if (map['bloodOxygenList'] != null) {
      // 保留null值，使用List<int?>
      final rawList = map['bloodOxygenList'] as List?;
      if (rawList != null) {
        bloodOxygenData = rawList.map((item) => item as int?).toList();
      }
    }

    return HistoryBloodOxygenData(
      startTime: map['startTime'] ?? 0,
      bloodOxygenList: bloodOxygenData,
      timeInterval: map['timeInterval'] ?? 5,
      historyDay: map['historyDay'] ?? '',
    );
  }

  /// 获取每小时血氧数据
  List<int> getHourlyBloodOxygen() {
    if (bloodOxygenList.isEmpty) return List.filled(24, 0);

    final hourlyData = <int>[];
    final minutesPerHour = 60;
    final dataPointsPerHour = minutesPerHour ~/ timeInterval;

    for (int hour = 0; hour < 24; hour++) {
      final startIndex = hour * dataPointsPerHour;
      final endIndex = (hour + 1) * dataPointsPerHour;

      if (startIndex < bloodOxygenList.length) {
        final hourBloodOxygen = bloodOxygenList.sublist(
            startIndex,
            endIndex > bloodOxygenList.length
                ? bloodOxygenList.length
                : endIndex);

        // 计算该小时的平均血氧（排除null和0值）
        final validHourBloodOxygen = hourBloodOxygen
            .where((value) => value != null && value > 0)
            .cast<int>()
            .toList();
        if (validHourBloodOxygen.isNotEmpty) {
          final avgBloodOxygen = (validHourBloodOxygen.reduce((a, b) => a + b) /
                  validHourBloodOxygen.length)
              .round();
          hourlyData.add(avgBloodOxygen);
        } else {
          hourlyData.add(0); // 该小时没有有效数据
        }
      } else {
        hourlyData.add(0);
      }
    }

    return hourlyData;
  }

  @override
  String toString() {
    return 'HistoryBloodOxygenData(startTime: $startTime, bloodOxygenList: ${bloodOxygenList.length} items, timeInterval: $timeInterval, historyDay: $historyDay)';
  }
}

/// HRV数据模型
class HrvData {
  final int hrv;
  final DateTime timestamp;

  const HrvData({
    required this.hrv,
    required this.timestamp,
  });

  factory HrvData.fromMap(Map<String, dynamic> map) {
    return HrvData(
      hrv: map['hrv'] ?? 0,
      timestamp: DateTime.now(),
    );
  }

  /// 获取HRV状态
  String get status {
    if (hrv >= 50) return '正常范围';
    if (hrv >= 20) return '偏低';
    return '较低';
  }

  @override
  String toString() {
    return 'HrvData(hrv: ${hrv}毫秒, timestamp: $timestamp)';
  }
}

/// 压力数据模型
class StressData {
  final int stress;
  final DateTime timestamp;

  const StressData({
    required this.stress,
    required this.timestamp,
  });

  factory StressData.fromMap(Map<String, dynamic> map) {
    return StressData(
      stress: map['stress'] ?? 0,
      timestamp: DateTime.now(),
    );
  }

  /// 获取压力状态
  String get status {
    if (stress <= 30) return '放松';
    if (stress <= 60) return '适中';
    if (stress <= 80) return '较高';
    return '高压';
  }

  @override
  String toString() {
    return 'StressData(stress: $stress, timestamp: $timestamp)';
  }
}

/// 心率数据模型（扩展）
class HeartRateData {
  final int heartRate;
  final DateTime timestamp;
  final bool isRealtime;

  const HeartRateData({
    required this.heartRate,
    required this.timestamp,
    this.isRealtime = false,
  });

  factory HeartRateData.fromMap(Map<String, dynamic> map,
      {bool isRealtime = false}) {
    return HeartRateData(
      heartRate: map['heartRate'] ?? 0,
      timestamp: DateTime.now(),
      isRealtime: isRealtime,
    );
  }

  /// 获取心率状态
  String get status {
    if (heartRate == 0) return '未测量';
    if (heartRate < 60) return '偏低';
    if (heartRate > 100) return '偏高';
    return '正常';
  }

  @override
  String toString() {
    return 'HeartRateData(heartRate: ${heartRate}bpm, timestamp: $timestamp, isRealtime: $isRealtime)';
  }
}

/// 每日数据模型
class DailyData {
  final DateTime date;
  final int steps;
  final int distance;
  final int calories;
  final int? time;
  final bool isToday;

  const DailyData({
    required this.date,
    required this.steps,
    required this.distance,
    required this.calories,
    this.time,
    this.isToday = false,
  });

  /// 获取完成度（0.0 - 1.0）
  double get stepsProgress => (steps / 8000.0).clamp(0.0, 1.0);
  double get caloriesProgress => (calories / 400.0).clamp(0.0, 1.0);
  double get timeProgress => ((time ?? 0) / 30.0).clamp(0.0, 1.0);

  /// 是否完成目标
  bool get isStepsCompleted => steps >= 8000;
  bool get isCaloriesCompleted => calories >= 400;
  bool get isTimeCompleted => (time ?? 0) >= 30;

  /// 获取历史日期枚举字符串
  String get historyDayString {
    if (isToday) {
      return 'TODAY';
    }

    final now = DateTime.now();
    final daysDiff = now.difference(date).inDays;

    if (daysDiff == 1) {
      return 'YESTERDAY';
    } else if (daysDiff >= 2 && daysDiff <= 14) {
      return 'DAYS_AGO_$daysDiff';
    } else {
      return 'TODAY'; // 默认返回今天
    }
  }

  @override
  String toString() {
    return 'DailyData(date: $date, steps: $steps, distance: $distance, calories: $calories, time: $time, isToday: $isToday)';
  }
}

/// 历史心率数据模型
class HistoryHeartRateData {
  final int startTime;
  final List<int?> heartRateList; // 保留null值
  final int timeInterval;
  final String historyDay;

  const HistoryHeartRateData({
    required this.startTime,
    required this.heartRateList,
    required this.timeInterval,
    required this.historyDay,
  });

  factory HistoryHeartRateData.fromMap(Map<String, dynamic> map) {
    // 保留null值，使用List<int?>
    final rawList = map['heartRateList'] as List?;
    final heartRateList = <int?>[];

    if (rawList != null) {
      heartRateList.addAll(rawList.map((item) => item as int?));
    }

    return HistoryHeartRateData(
      startTime: map['startTime'] ?? 0,
      heartRateList: heartRateList,
      timeInterval: map['timeInterval'] ?? 5,
      historyDay: map['historyDay'] ?? 'TODAY',
    );
  }

  /// 获取有效的心率数据（过滤掉null和0值）
  List<int> get validHeartRateList {
    return heartRateList
        .where((rate) => rate != null && rate > 0)
        .cast<int>()
        .toList();
  }

  /// 获取平均心率
  int get averageHeartRate {
    final validRates = validHeartRateList;
    if (validRates.isEmpty) return 0;
    return (validRates.reduce((a, b) => a + b) / validRates.length).round();
  }

  /// 获取每小时的心率数据
  List<int> get hourlyHeartRateData {
    final hourlyData = <int>[];
    final validRates = validHeartRateList;

    if (validRates.isEmpty) return hourlyData;

    // 根据时间间隔计算每小时的数据点数量
    final pointsPerHour = 60 ~/ timeInterval;

    for (int hour = 0; hour < 24; hour++) {
      final startIndex = hour * pointsPerHour;
      final endIndex = (hour + 1) * pointsPerHour;

      if (startIndex < heartRateList.length) {
        final hourRates = heartRateList.sublist(startIndex,
            endIndex > heartRateList.length ? heartRateList.length : endIndex);

        // 计算该小时的平均心率（排除null和0值）
        final validHourRates = hourRates
            .where((rate) => rate != null && rate > 0)
            .cast<int>()
            .toList();
        if (validHourRates.isNotEmpty) {
          final avgRate =
              (validHourRates.reduce((a, b) => a + b) / validHourRates.length)
                  .round();
          hourlyData.add(avgRate);
        } else {
          hourlyData.add(0); // 该小时没有有效数据
        }
      } else {
        hourlyData.add(0);
      }
    }

    return hourlyData;
  }

  @override
  String toString() {
    return 'HistoryHeartRateData(startTime: $startTime, heartRateList: ${heartRateList.length} items, timeInterval: $timeInterval, historyDay: $historyDay)';
  }
}

/// 戒指连接状态枚举
enum RingConnectionState { disconnected, connecting, connected }

/// 戒指服务类
/// 负责管理戒指设备的连接、数据获取和状态管理
class RingService extends GetxService {
  static const String _channelName = 'com.azring.azring/ring_data';
  static const String _tag = 'RingService';

  late final MethodChannel _methodChannel;
  late final DeviceStorageService _deviceStorage;

  // 响应式状态变量
  final Rx<RingConnectionState> _connectionState =
      RingConnectionState.disconnected.obs;
  final RxList<RingDevice> _scannedDevices = <RingDevice>[].obs;
  final Rx<RingDevice?> _connectedDevice = Rx<RingDevice?>(null);
  final Rx<StepsData?> _stepsData = Rx<StepsData?>(null);
  final Rx<SleepData?> _sleepData = Rx<SleepData?>(null);
  final RxInt _heartRate = 0.obs;
  final RxInt _battery = 0.obs;
  final RxBool _isCharging = false.obs; // 是否正在充电
  final RxBool _isScanning = false.obs;

  // 设备绑定状态
  final RxBool _isDeviceBound = false.obs;

  // 防止重复初始化的状态管理
  final RxBool _isInitializingDevice = false.obs;

  // 数据同步加载状态（连接后数据上报中）
  final RxBool _isDataSyncing = false.obs;

  // 数据上报完成通知（用于通知外部可以查询详情数据）
  final RxBool _dataReportCompleted = false.obs;

  // 防止重复上报的标记（使用 Set 存储已上报的数据类型和时间戳）
  final Set<String> _reportedDataKeys = <String>{};

  // 数据上报计数器（用于跟踪上报进度）
  final RxInt _pendingReportCount = 0.obs;
  final RxBool _allDataReported = false.obs;

  // HRV优先上报标志：true表示HRV已上报，其他数据可以上报
  final RxBool _hrvReportCompleted = false.obs;

  // 待上报数据队列（HRV未完成时，其他数据先缓存）
  final List<Function> _pendingReportQueue = [];

  // 数据同步进度追踪（用于进度条显示）
  final RxInt _syncProgress = 0.obs; // 当前进度 (0-100)
  final RxInt _totalSyncSteps = 7.obs; // 总步骤数
  final RxInt _completedSyncSteps = 0.obs; // 已完成步骤数

  // 新增数据模型的响应式变量
  final Rx<BloodOxygenData?> _bloodOxygenData = Rx<BloodOxygenData?>(null);
  final Rx<HistoryBloodOxygenData?> _historyBloodOxygenData =
      Rx<HistoryBloodOxygenData?>(null);
  final Rx<HrvData?> _hrvData = Rx<HrvData?>(null);
  final Rx<List<int?>?> _historyHrvList = Rx<List<int?>?>(null); // 添加历史HRV列表
  final Rx<StressData?> _stressData = Rx<StressData?>(null);
  final Rx<HeartRateData?> _heartRateData = Rx<HeartRateData?>(null);
  final Rx<HistoryHeartRateData?> _historyHeartRateData =
      Rx<HistoryHeartRateData?>(null);

  // 今日压力列表数据（保留null值）
  final RxList<int?> _todayStressList = <int?>[].obs;

  // 多天数据缓存（用于组合上报）
  final Map<String, List<int?>> _multiDayHeartRateData = {};
  final Map<String, List<int?>> _multiDayHrvData = {};
  final Map<String, List<int?>> _multiDayStressData = {};
  final Map<String, List<int?>> _multiDayBloodOxygenData = {};
  final Map<String, List<int>> _multiDayEventData = {};
  final Map<String, Map<String, dynamic>> _multiDaySportData = {}; // 运动记录数据缓存
  final Map<String, List<int>> _multiDaySportDetailData =
      {}; // 运动明细数据缓存（每半小时步数）

  // 保存 timeInterval 的值（用于上报时使用）
  int _cachedTimeInterval = 5; // 默认值为5分钟

  // 运动记录数据
  final Rx<RingSportRecord?> _sportRecord = Rx<RingSportRecord?>(null);

  // 历史训练列表数据
  final RxList<Map<String, dynamic>> _historyTrainingList =
      <Map<String, dynamic>>[].obs;

  // 训练详情数据（SDK返回的完整数据）
  final Rx<Map<String, dynamic>?> _trainingDetails =
      Rx<Map<String, dynamic>?>(null);

  // 当前训练状态
  final Rx<String> _trainingState = 'idle'.obs;

  // 支持的训练类型列表
  final RxList<String> _supportedTrainingTypes = <String>[].obs;

  // 锻炼详情数据（旧的，保留兼容性）
  final Rx<Map<String, dynamic>?> _exerciseDetail =
      Rx<Map<String, dynamic>?>(null);

  // 测量状态
  final RxBool _isHeartRateMeasuring = false.obs;
  final RxBool _isBloodOxygenMeasuring = false.obs;
  final RxBool _isHrvMeasuring = false.obs;
  final RxBool _isStressMeasuring = false.obs;

  // 过去7天的数据（用于显示）
  final RxList<DailyData> _weeklyData = <DailyData>[].obs;

  // 过去14天的完整数据（用于查询）
  final RxList<DailyData> _allHistoryData = <DailyData>[].obs;

  // 上次上报的睡眠结束时间（用于判断是否是新的睡眠数据）
  String? _lastReportedSleepEndTime;

  // 【最终方案】睡眠数据基于索引的缓存
  final Map<int, Map<String, dynamic>> _sleepDetailsCache = {};
  final Map<int, Map<String, dynamic>> _sleepInfoCache = {};

  // 【新增】记录已查询的索引，避免重复查询
  final Set<int> _queriedSleepIndices = {};

  // 【新增】当前正在查询的索引（用于顺序查询）
  int? _currentQueryingIndex;

  // 【新增】等待上报完成的 Completer
  Completer<void>? _sleepReportCompleter;

  // 【新增】是否正在查询睡眠数据（防止重复查询）
  bool _isQueryingSleepData = false;

  // Getters
  RingConnectionState get connectionState => _connectionState.value;
  List<RingDevice> get scannedDevices => _scannedDevices;
  RingDevice? get connectedDevice => _connectedDevice.value;
  StepsData? get stepsData => _stepsData.value;
  bool get isDeviceBound => _isDeviceBound.value;

  /// 更新步数数据（用于从API获取的数据）
  void updateStepsDataFromApi(StepsData newStepsData) {
    _stepsData.value = newStepsData;
    developer.log('✅ 从API更新步数数据: $newStepsData', name: _tag);
  }

  SleepData? get sleepData => _sleepData.value;
  int get heartRate => _heartRate.value;
  int get battery => _battery.value;
  bool get isCharging => _isCharging.value; // 是否正在充电
  bool get isScanning => _isScanning.value;
  bool get isConnected => connectionState == RingConnectionState.connected;
  bool get isDataSyncing => _isDataSyncing.value; // 数据同步中
  int get pendingReportCount => _pendingReportCount.value; // 待上报数据数量
  int get syncProgress => _syncProgress.value; // 同步进度 (0-100)
  List<DailyData> get weeklyData => _weeklyData;
  List<DailyData> get allHistoryData => _allHistoryData;
  bool get dataReportCompleted => _dataReportCompleted.value; // 数据上报是否完成

  // 新增数据的Getters
  BloodOxygenData? get bloodOxygenData => _bloodOxygenData.value;
  HistoryBloodOxygenData? get historyBloodOxygenData =>
      _historyBloodOxygenData.value;
  HrvData? get hrvData => _hrvData.value;
  List<int?>? get historyHrvList => _historyHrvList.value; // 添加历史HRV列表getter
  StressData? get stressData => _stressData.value;
  HeartRateData? get heartRateData => _heartRateData.value;
  HistoryHeartRateData? get historyHeartRateData => _historyHeartRateData.value;
  RingSportRecord? get sportRecord => _sportRecord.value;

  // 测量状态的Getters
  bool get isHeartRateMeasuring => _isHeartRateMeasuring.value;
  bool get isBloodOxygenMeasuring => _isBloodOxygenMeasuring.value;
  bool get isHrvMeasuring => _isHrvMeasuring.value;
  bool get isStressMeasuring => _isStressMeasuring.value;

  // 响应式变量的公共访问器
  Rx<RingConnectionState> get connectionStateRx => _connectionState;
  RxInt get batteryRx => _battery;
  RxBool get isChargingRx => _isCharging; // 充电状态的响应式访问器
  RxInt get heartRateRx => _heartRate;
  RxList<DailyData> get weeklyDataRx => _weeklyData;
  Rx<BloodOxygenData?> get bloodOxygenDataRx => _bloodOxygenData;
  Rx<HistoryBloodOxygenData?> get historyBloodOxygenDataRx =>
      _historyBloodOxygenData;
  Rx<HrvData?> get hrvDataRx => _hrvData;
  Rx<StressData?> get stressDataRx => _stressData;
  Rx<HeartRateData?> get heartRateDataRx => _heartRateData;
  Rx<HistoryHeartRateData?> get historyHeartRateDataRx => _historyHeartRateData;
  Rx<SleepData?> get sleepDataRx => _sleepData;
  Rx<RingSportRecord?> get sportRecordRx => _sportRecord;
  RxList<int?> get todayStressListRx => _todayStressList;
  RxList<Map<String, dynamic>> get historyTrainingListRx =>
      _historyTrainingList;
  Rx<Map<String, dynamic>?> get trainingDetailsRx => _trainingDetails;
  Rx<String> get trainingStateRx => _trainingState;
  RxList<String> get supportedTrainingTypesRx => _supportedTrainingTypes;
  Rx<Map<String, dynamic>?> get exerciseDetailRx => _exerciseDetail;
  RxBool get isDeviceBoundRx => _isDeviceBound;
  RxBool get isDataSyncingRx => _isDataSyncing;
  RxBool get dataReportCompletedRx => _dataReportCompleted; // 数据上报完成的响应式访问器

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeMethodChannel();
    _initializeDeviceStorage();
    _initializeWeeklyData();
    developer.log('🔗 戒指服务初始化完成', name: _tag);
  }

  /// 初始化过去21天的数据（显示最近7天，支持查询21天）
  void _initializeWeeklyData() {
    final now = DateTime.now();
    final allData = <DailyData>[];

    // 初始化过去21天的数据，确保覆盖完整的周视图
    for (int i = 20; i >= 0; i--) {
      final date = now.subtract(Duration(days: i));
      final isToday = i == 0;

      // 使用真实数据或默认值
      final steps = isToday ? (_stepsData.value?.steps ?? 0) : 0;
      final calories = isToday ? (_stepsData.value?.calories ?? 0) : 0;
      final distance = isToday ? (_stepsData.value?.distance ?? 0) : 0;
      final time = isToday ? (_stepsData.value?.time ?? 0) : 0;

      allData.add(DailyData(
        date: date,
        steps: steps,
        distance: distance,
        calories: calories,
        time: time,
        isToday: isToday,
      ));
    }

    // 只显示最近7天，但保存21天数据供查询使用
    final displayData = allData.skip(14).toList(); // 最近7天
    _weeklyData.assignAll(displayData);

    // 保存完整的21天数据到另一个变量
    _allHistoryData.assignAll(allData);

    developer.log(
        '📊 初始化21天数据完成: 总数=${allData.length}天, 显示${displayData.length}天',
        name: _tag);
  }

  /// 获取指定日期的步数数据
  Future<void> fetchStepsDataForDate(int dayIndex) async {
    if (dayIndex < 0 || dayIndex >= _weeklyData.length) {
      developer.log('❌ 无效的日期索引: $dayIndex', name: _tag);
      return;
    }

    final selectedDay = _weeklyData[dayIndex];
    developer.log(
        '📊 获取日期数据: ${selectedDay.date}, historyDay=${selectedDay.historyDayString}',
        name: _tag);

    try {
      final success = await queryStepsForDate(selectedDay.historyDayString);
      if (!success) {
        developer.log('❌ 获取日期数据失败', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 获取日期数据异常: $e', name: _tag);
    }
  }

  /// 根据历史日期字符串获取步数数据（支持14天内任意日期）
  Future<void> fetchStepsDataByHistoryDay(String historyDayString) async {
    developer.log('📊 根据历史日期获取数据: $historyDayString', name: _tag);

    try {
      final success = await queryStepsForDate(historyDayString);
      if (!success) {
        developer.log('❌ 获取历史日期数据失败: $historyDayString', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 获取历史日期数据异常: $e', name: _tag);
    }
  }

  /// 根据天数获取历史数据（1=昨天，2=前天，...，21=21天前）
  Future<void> fetchStepsDataByDaysAgo(int daysAgo) async {
    if (daysAgo < 1 || daysAgo > 21) {
      developer.log('❌ 无效的天数: $daysAgo，支持范围1-21天', name: _tag);
      return;
    }

    final historyDayString = daysAgo == 1 ? 'YESTERDAY' : 'DAYS_AGO_$daysAgo';
    await fetchStepsDataByHistoryDay(historyDayString);
  }

  /// 查询一周历史数据（上周日到本周六）
  Future<bool> queryWeeklyHistorySteps() async {
    developer.log('📊 开始查询一周历史数据', name: _tag);

    try {
      final now = DateTime.now();
      final today = now.weekday; // 1=周一，7=周日

      // 计算上周日的日期
      final daysToLastSunday = today == 7 ? 0 : today;
      final lastSunday = now.subtract(Duration(days: daysToLastSunday));

      // 计算本周六的日期
      final daysToSaturday = 7 - today;
      final thisSaturday = now.add(Duration(days: daysToSaturday));

      developer.log(
          '📅 查询范围: ${lastSunday.toString().substring(0, 10)} 到 ${thisSaturday.toString().substring(0, 10)}',
          name: _tag);

      // 查询每一天的数据
      for (int i = 0; i < 7; i++) {
        final date = lastSunday.add(Duration(days: i));
        final daysAgo = now.difference(date).inDays;

        String historyDay;
        if (daysAgo == 0) {
          historyDay = 'TODAY';
        } else if (daysAgo == 1) {
          historyDay = 'YESTERDAY';
        } else {
          historyDay = 'DAYS_AGO_$daysAgo';
        }

        developer.log(
            '📊 查询日期: ${date.toString().substring(0, 10)} -> $historyDay',
            name: _tag);

        final success = await queryStepsForDate(historyDay);
        if (!success) {
          developer.log('⚠️ 查询失败: $historyDay', name: _tag);
        }

        // 添加延迟避免请求过于频繁
        await Future.delayed(Duration(milliseconds: 100));
      }

      developer.log('✅ 一周历史数据查询完成', name: _tag);
      return true;
    } catch (e) {
      developer.log('❌ 查询一周历史数据异常: $e', name: _tag);
      return false;
    }
  }

  /// 初始化方法通道
  Future<void> _initializeMethodChannel() async {
    _methodChannel = const MethodChannel(_channelName);
    _methodChannel.setMethodCallHandler(_handleMethodCall);
  }

  /// 初始化设备存储服务
  void _initializeDeviceStorage() {
    try {
      _deviceStorage = Get.find<DeviceStorageService>();
      developer.log('💾 设备存储服务已初始化', name: _tag);
    } catch (e) {
      developer.log('❌ 设备存储服务初始化失败: $e', name: _tag);
      // 如果找不到 DeviceStorageService，创建一个临时的
      _deviceStorage = Get.put<DeviceStorageService>(DeviceStorageService(),
          permanent: true);
      developer.log('🔄 已重新注册设备存储服务', name: _tag);
    }
  }

  /// 处理来自原生端的方法调用
  Future<void> _handleMethodCall(MethodCall call) async {
    developer.log('📱 收到原生调用: ${call.method}, 参数: ${call.arguments}',
        name: _tag);

    try {
      switch (call.method) {
        case 'onDeviceFound':
          _handleDeviceFound(call.arguments);
          break;
        case 'onScanComplete':
          _handleScanComplete(call.arguments);
          break;
        case 'onConnectionStateChanged':
          _handleConnectionStateChanged(call.arguments);
          break;
        case 'onStepsDataReceived':
          _handleStepsDataReceived(call.arguments);
          break;
        case 'onSleepDataReceived':
          _handleSleepDataReceived(call.arguments);
          break;
        case 'onSleepDetailsReceived':
          _handleSleepDetailsReceived(call.arguments);
          break;
        case 'onSleepInfoReceived':
          _handleSleepInfoReceived(call.arguments);
          break;
        case 'onHeartRateReceived':
          _handleHeartRateReceived(call.arguments);
          break;
        case 'onRealtimeHeartRate':
          _handleRealtimeHeartRate(call.arguments);
          break;
        case 'onBatteryReceived':
          _handleBatteryReceived(call.arguments);
          break;
        case 'onBloodOxygenReceived':
          _handleBloodOxygenReceived(call.arguments);
          break;
        case 'onHrvReceived':
          _handleHrvReceived(call.arguments);
          break;
        case 'onStressReceived':
          _handleStressReceived(call.arguments);
          break;
        case 'onStressListReceived':
          await _handleStressListReceived(call.arguments);
          break;
        case 'reportSleepDetailData':
          Map<String, dynamic> sleepData;
          if (call.arguments is Map<String, dynamic>) {
            sleepData = call.arguments as Map<String, dynamic>;
          } else if (call.arguments is Map) {
            sleepData = Map<String, dynamic>.from(call.arguments);
            developer.log(
                '🔄 转换Map类型: ${call.arguments.runtimeType} -> Map<String, dynamic>',
                name: _tag);
          } else {
            developer.log('❌ 无效的数据类型: ${call.arguments.runtimeType}',
                name: _tag);
            break;
          }
          await _handleReportSleepDetailData(sleepData);
          break;
        case 'onBloodPressureReceived':
          _handleBloodPressureReceived(call.arguments);
          break;
        case 'onFirmwareVersionReceived':
          _handleFirmwareVersionReceived(call.arguments);
          break;
        case 'onHistoryHeartRateReceived':
          _handleHistoryHeartRateReceived(call.arguments);
          break;
        case 'onHistoryBloodOxygenReceived':
          _handleHistoryBloodOxygenReceived(call.arguments);
          break;
        case 'onHistoryHrvReceived':
          _handleHistoryHrvReceived(call.arguments);
          break;
        case 'onExerciseDetailsReceived':
          _handleExerciseDetailsReceived(call.arguments);
          break;
        case 'onDailyExerciseDetailsReceived':
          _handleDailyExerciseDetailsReceived(call.arguments);
          break;
        case 'onActionDetailsReceived':
          await _handleActionDetailsReceived(call.arguments);
          break;
        case 'onHistoryTrainingReceived':
          _handleHistoryTrainingReceived(call.arguments);
          break;
        case 'onTrainingDataReceived':
          _handleTrainingDataReceived(call.arguments);
          break;
        case 'onHistorySleepListReceived':
          await _handleHistorySleepListReceived(call.arguments);
          break;
        case 'onSleepChronotypeReceived':
          _handleSleepChronotypeReceived(call.arguments);
          break;
        // 训练相关回调
        case 'onSupportTrainingListReceived':
          _handleSupportTrainingListReceived(call.arguments);
          break;
        case 'onTrainingStateChanged':
          _handleTrainingStateChanged(call.arguments);
          break;
        case 'onTrainingDetailsReceived':
          _handleTrainingDetailsReceived(call.arguments);
          break;
        case 'onTrainingGoalReached':
          _handleTrainingGoalReached(call.arguments);
          break;
        default:
          developer.log('⚠️ 未处理的方法调用: ${call.method}', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 处理方法调用失败: $e', name: _tag);
    }
  }

  /// 处理发现设备事件
  void _handleDeviceFound(dynamic arguments) {
    Map<String, dynamic>? deviceMap;

    if (arguments is Map<String, dynamic>) {
      deviceMap = arguments;
    } else if (arguments is Map) {
      deviceMap = Map<String, dynamic>.from(arguments);
    }

    if (deviceMap != null) {
      try {
        final device = RingDevice.fromMap(deviceMap);
        developer.log('📍 发现设备: ${device.name} (${device.address})',
            name: _tag);

        final existingIndex =
            _scannedDevices.indexWhere((d) => d.address == device.address);
        if (existingIndex >= 0) {
          _scannedDevices[existingIndex] = device;
        } else {
          _scannedDevices.add(device);
        }
      } catch (e) {
        developer.log('❌ 解析设备数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理扫描完成事件
  void _handleScanComplete(dynamic arguments) {
    _isScanning.value = false;
    final deviceCount = arguments as int;
    developer.log('🔍 扫描完成，发现 $deviceCount 个设备', name: _tag);
  }

  /// 处理连接状态变化事件
  Future<void> _handleConnectionStateChanged(dynamic arguments) async {
    Map<String, dynamic>? stateMap;

    if (arguments is Map<String, dynamic>) {
      stateMap = arguments;
    } else if (arguments is Map) {
      stateMap = Map<String, dynamic>.from(arguments);
    }

    if (stateMap != null && stateMap.containsKey('state')) {
      final stateString = stateMap['state'] as String;
      final newState = _parseConnectionState(stateString);
      final oldState = _connectionState.value;
      _connectionState.value = newState;
      developer.log('🔗 连接状态: $stateString', name: _tag);

      if (newState == RingConnectionState.connected &&
          oldState != RingConnectionState.connected) {
        // ✅ 添加 await 确保连接成功处理完整执行
        try {
          print('🔗 [RingService] 检测到连接成功，开始执行 _handleConnectionSuccess()');
          await _handleConnectionSuccess();
          print('✅ [RingService] _handleConnectionSuccess() 执行完成');
        } catch (e, stackTrace) {
          print('❌ [RingService] _handleConnectionSuccess() 执行异常: $e');
          print('❌ [RingService] 堆栈跟踪: $stackTrace');
          developer.log('❌ 连接成功处理异常: $e\n堆栈: $stackTrace', name: _tag);
        }
      } else if (newState == RingConnectionState.disconnected) {
        // 断开连接时清除数据同步状态
        _isDataSyncing.value = false;
        developer.log('🔌 设备断开连接，清除数据同步状态', name: _tag);

        // 自动重连
        _handleAutoReconnect();
      }
    }
  }

  /// 处理自动重连
  void _handleAutoReconnect() {
    // 延迟3秒后尝试重连，避免频繁重连
    Future.delayed(const Duration(seconds: 3), () async {
      // 检查是否仍然处于断开状态
      if (_connectionState.value == RingConnectionState.disconnected) {
        developer.log('🔄 检测到断开连接，尝试自动重连...', name: _tag);
        final success = await autoReconnect();
        if (!success) {
          developer.log('❌ 自动重连失败', name: _tag);
        }
      }
    });
  }

  /// 处理详细步数数据接收事件
  void _handleStepsDataReceived(dynamic arguments) {
    Map<String, dynamic>? stepsMap;

    if (arguments is Map<String, dynamic>) {
      stepsMap = arguments;
    } else if (arguments is Map) {
      stepsMap = Map<String, dynamic>.from(arguments);
    }

    if (stepsMap != null) {
      try {
        final stepsData = StepsData.fromMap(stepsMap);
        _stepsData.value = stepsData;

        // 获取设备序列号
        final deviceSn = getCurrentDeviceSn();

        // 判断是否是历史数据（包含 historyDay 字段）
        final isHistoryData = stepsMap.containsKey('historyDay');

        if (stepsMap.containsKey('stepsList')) {
          developer.log('✅ 收到详细步数: ${stepsData.steps}步', name: _tag);
          final hourlySteps = stepsData.hourlySteps;
          if (hourlySteps != null &&
              hourlySteps.isNotEmpty &&
              deviceSn.isNotEmpty) {
            // 确定日期和 historyDay
            String historyDay;
            if (isHistoryData && stepsMap.containsKey('historyDay')) {
              historyDay = stepsMap['historyDay'] as String;
            } else {
              historyDay = 'TODAY';
            }

            // 过滤掉null值，转换为List<int>
            final validStepsList = hourlySteps.whereType<int>().toList();

            // 缓存运动明细数据
            _multiDaySportDetailData[historyDay] = validStepsList;
            developer.log(
                '📊 缓存运动明细数据: $historyDay (${_multiDaySportDetailData.length}/8天)',
                name: _tag);

            // 如果收集满8天（今天+7天前），立即上报
            if (_multiDaySportDetailData.length >= 8) {
              developer.log('✅ 运动明细数据已收集满8天，开始上报', name: _tag);
              _reportMultiDaySportDetail();
            }
          }
        } else if (isHistoryData) {
          developer.log(
              '✅ 收到历史步数: ${stepsData.steps}步 (historyDay: ${stepsMap['historyDay']})',
              name: _tag);
        } else {
          developer.log('✅ 收到当前步数: ${stepsData.steps}步', name: _tag);
        }

        // 收集运动记录数据（包括今天和历史数据）
        if (deviceSn.isNotEmpty && stepsData.steps > 0) {
          // 确定日期
          String dailyValue;
          if (isHistoryData && stepsMap.containsKey('historyDay')) {
            // 历史数据：根据 historyDay 计算日期
            final historyDayStr = stepsMap['historyDay'] as String;
            dailyValue = _convertHistoryDayToDate(historyDayStr);
          } else {
            // 当前数据：使用今天的日期
            final now = DateTime.now();
            dailyValue =
                '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
          }

          // 缓存运动记录数据（需要进行单位转换）
          // SDK 返回的 distance 单位是厘米，需要除以 100 得到米
          // SDK 返回的 calories 单位是 0.0001 卡路里，需要除以 10000 得到卡路里
          _multiDaySportData[dailyValue] = {
            'dailyValue': dailyValue,
            'steps': stepsData.steps,
            'distance': (stepsData.distance / 100).round(), // 厘米转米
            'calories': (stepsData.calories / 10000).round(), // 转换为卡路里
            'sportTime': stepsData.time ?? 0,
          };

          developer.log(
              '📊 缓存运动记录数据: $dailyValue (${_multiDaySportData.length}/8天)',
              name: _tag);

          // 如果收集满8天（今天+7天前），立即上报
          if (_multiDaySportData.length >= 8) {
            developer.log('✅ 运动记录数据已收集满8天，开始上报', name: _tag);
            _reportMultiDaySport(deviceSn);
          }
        }
      } catch (e) {
        developer.log('❌ 解析步数数据失败: $e', name: _tag);
      }
    }
  }

  /// 发送运动明细数据到接口（已废弃，改用批量上报）
  @Deprecated('使用批量上报方式，数据会自动收集并上报')
  Future<void> sendSportDetailToApi({
    String? deviceSn, // 改为可选参数，优先使用当前设备
    required String historyDay,
    required List<int> stepsList,
  }) async {
    try {
      developer.log('📤 开始发送运动明细数据到接口', name: _tag);

      // 获取当前设备序列号
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备未连接，无法发送运动明细数据', name: _tag);
        return;
      }

      // 创建运动明细数据
      final sportDetail = RingSportDetail.fromStepsData(
        deviceSn: deviceSn,
        historyDay: historyDay,
        stepsList: stepsList,
      );

      developer.log('📊 运动明细数据: $sportDetail', name: _tag);

      final result = await DefaultApi()
          .addSportDetailPost<Map<String, dynamic>>(sportDetail: sportDetail);

      if (result != null) {
        developer.log('✅ 运动明细数据发送成功: $result', name: _tag);
      } else {
        developer.log('⚠️ 运动明细数据发送失败或无响应', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 发送运动明细数据到接口失败: $e', name: _tag);
    }
  }

  /// 处理睡眠数据接收事件
  void _handleSleepDataReceived(dynamic arguments) {
    developer.log('😴 收到睡眠数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    // 处理不同类型的Map，转换为 Map<String, dynamic>
    Map<String, dynamic>? sleepMap;

    if (arguments is Map<String, dynamic>) {
      sleepMap = arguments;
    } else if (arguments is Map) {
      sleepMap = Map<String, dynamic>.from(arguments);
      developer.log(
          '🔄 转换睡眠Map类型: ${arguments.runtimeType} -> Map<String, dynamic>',
          name: _tag);
    }

    if (sleepMap != null) {
      try {
        final sleepData = SleepData.fromMap(sleepMap);
        _sleepData.value = sleepData;
        developer.log('✅ 睡眠数据更新: $sleepData', name: _tag);

        // 打印详细的睡眠信息
        developer.log(
            '📊 睡眠详情: 总时长=${sleepData.totalSleepTime}分钟, 深睡=${sleepData.deepSleepTime}分钟, 浅睡=${sleepData.lightSleepTime}分钟, REM=${sleepData.remSleepTime}分钟, 醒来次数=${sleepData.awakeTimes}',
            name: _tag);

        // 立即上报睡眠数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty && sleepData.totalSleepTime > 0) {
          // _autoReportSingleSleepData(deviceSn, sleepData);
        }
      } catch (e) {
        developer.log('❌ 解析睡眠数据失败: $e', name: _tag);
        developer.log('❌ 原始数据: $sleepMap', name: _tag);
      }
    } else {
      developer.log('❌ 睡眠数据格式错误，无法转换为Map: ${arguments.runtimeType}',
          name: _tag);
    }
  }

  /// 处理睡眠详情接收事件
  void _handleSleepDetailsReceived(dynamic arguments) {
    Map<String, dynamic>? detailsMap;

    if (arguments is Map<String, dynamic>) {
      detailsMap = arguments;
    } else if (arguments is Map) {
      detailsMap = Map<String, dynamic>.from(arguments);
    }

    if (detailsMap != null && detailsMap.containsKey('index')) {
      final index = detailsMap['index'] as int;
      final startDate = detailsMap['startDate'] as String?;
      final type = detailsMap['type'] as String?;
      developer.log('📊 [$index] 收到睡眠详情: startDate=$startDate, type=$type',
          name: _tag);

      // 【简化】使用索引作为 key 存储
      _sleepDetailsCache[index] = detailsMap;

      // 【修复】立即检查是否可以组合数据（可能 info 已经先到了）
      _checkAndCombineSleepData(index);

      // 【新增】如果当前索引不是正在查询的索引，也尝试配对
      // 这样可以处理数据乱序到达的情况
      if (_currentQueryingIndex != null && index != _currentQueryingIndex) {
        developer.log('🔄 [$index] 收到非当前查询索引的数据，尝试配对', name: _tag);
        final cachedInfo = _sleepInfoCache[index];
        if (cachedInfo != null) {
          developer.log('✅ [$index] 找到对应的 info 数据，开始组合', name: _tag);
          _combineSleepDataAndReport(index, detailsMap, cachedInfo);
        }
      }
    } else {
      developer.log('⚠️ 睡眠详情数据缺少 index 字段: $detailsMap', name: _tag);
    }
  }

  /// 处理睡眠信息接收事件
  void _handleSleepInfoReceived(dynamic arguments) {
    Map<String, dynamic>? infoMap;

    if (arguments is Map<String, dynamic>) {
      infoMap = arguments;
    } else if (arguments is Map) {
      infoMap = Map<String, dynamic>.from(arguments);
    }

    if (infoMap != null && infoMap.containsKey('index')) {
      final index = infoMap['index'] as int;
      final totalTime = infoMap['totalTime'];
      final detailsCount = (infoMap['details'] as List?)?.length ?? 0;

      developer.log(
          '📋 [$index] 收到睡眠信息: totalTime=$totalTime, details数量=$detailsCount',
          name: _tag);

      // 【简化】使用索引作为 key 存储
      _sleepInfoCache[index] = infoMap;

      // 【修复】立即检查是否可以组合数据（可能 details 已经先到了）
      _checkAndCombineSleepData(index);

      // 【新增】如果当前索引不是正在查询的索引，也尝试配对
      // 这样可以处理数据乱序到达的情况
      if (_currentQueryingIndex != null && index != _currentQueryingIndex) {
        developer.log('🔄 [$index] 收到非当前查询索引的数据，尝试配对', name: _tag);
        final cachedDetails = _sleepDetailsCache[index];
        if (cachedDetails != null) {
          developer.log('✅ [$index] 找到对应的 details 数据，开始组合', name: _tag);
          _combineSleepDataAndReport(index, cachedDetails, infoMap);
        }
      }
    } else {
      developer.log('⚠️ 睡眠信息数据缺少 index 字段', name: _tag);
    }
  }

  /// 【最终方案】检查并组合睡眠数据（基于索引）
  void _checkAndCombineSleepData(int index) {
    // 【关键修复】只处理当前正在查询的索引
    if (_currentQueryingIndex != null && index != _currentQueryingIndex) {
      developer.log('⚠️ [$index] 不是当前查询的索引（当前: $_currentQueryingIndex），忽略',
          name: _tag);
      return;
    }

    final details = _sleepDetailsCache[index];
    final info = _sleepInfoCache[index];

    developer.log(
        '🔍 [$index] 检查数据完整性: details=${details != null}, info=${info != null}',
        name: _tag);

    // 只要 details 和 info 都存在就可以组合数据
    if (details != null && info != null) {
      developer.log('✅ [$index] 睡眠数据已齐全，开始组合', name: _tag);
      _combineSleepDataAndReport(index, details, info);

      // 【关键】通知等待的查询可以继续
      if (_sleepReportCompleter != null &&
          !_sleepReportCompleter!.isCompleted) {
        _sleepReportCompleter!.complete();
      }
    } else {
      developer.log(
          '⏳ [$index] 等待数据齐全 (details: ${details != null}, info: ${info != null})',
          name: _tag);

      // 【修复】延长超时时间到 10 秒，并且不清除缓存
      // 因为 details 和 info 可能分两次到达，清除缓存会导致后续数据无法配对
      Future.delayed(const Duration(seconds: 10), () {
        final latestDetails = _sleepDetailsCache[index];
        final latestInfo = _sleepInfoCache[index];

        if (latestDetails != null && latestInfo != null) {
          // 数据已齐全，已经在之前组合过了
          return;
        }

        // 【修复】数据仍不齐全，但不清除缓存，只记录警告
        // 保留缓存，等待另一半数据到达
        if (latestDetails != null || latestInfo != null) {
          developer.log(
              '⚠️ [$index] 超时：数据不齐全 (details: ${latestDetails != null}, info: ${latestInfo != null})，保留缓存等待另一半数据',
              name: _tag);
        }

        // 【关键】通知等待的查询可以继续（即使数据不齐全）
        if (_sleepReportCompleter != null &&
            !_sleepReportCompleter!.isCompleted &&
            index == _currentQueryingIndex) {
          _sleepReportCompleter!.complete();
        }
      });
    }
  }

  /// 组合睡眠数据并上报
  void _combineSleepDataAndReport(
      int index, Map<String, dynamic> details, Map<String, dynamic> info) {
    try {
      // 从 startDate 计算 dailyValue (格式: yyyy-MM-dd)
      String dailyValue = '';
      final startDateStr = details['startDate']?.toString() ?? '';
      if (startDateStr.isNotEmpty) {
        try {
          // 解析日期字符串 "Sun Nov 09 04:24:00 GMT+08:00 2025"
          final dateMatch = RegExp(
                  r'(\w+)\s+(\w+)\s+(\d+)\s+\d+:\d+:\d+\s+GMT[+-]\d+:\d+\s+(\d+)')
              .firstMatch(startDateStr);
          if (dateMatch != null) {
            final monthStr = dateMatch.group(2);
            final day = dateMatch.group(3);
            final year = dateMatch.group(4);

            // 月份映射
            final monthMap = {
              'Jan': '01',
              'Feb': '02',
              'Mar': '03',
              'Apr': '04',
              'May': '05',
              'Jun': '06',
              'Jul': '07',
              'Aug': '08',
              'Sep': '09',
              'Oct': '10',
              'Nov': '11',
              'Dec': '12'
            };

            final month = monthMap[monthStr] ?? '01';
            dailyValue = '$year-$month-${day?.padLeft(2, '0')}';
          }
        } catch (e) {
          developer.log('❌ [$index] 解析日期失败: $e', name: _tag);
          // 使用当前日期作为 fallback
          final now = DateTime.now();
          dailyValue =
              '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
        }
      }

      // 移除不需要的字段
      final cleanedInfo = Map<String, dynamic>.from(info);
      cleanedInfo.remove('rawInfo');
      cleanedInfo.remove('index');

      final cleanedDetails = Map<String, dynamic>.from(details);
      cleanedDetails.remove('index');

      // 检查 info 中的 details 字段
      final infoDetails = cleanedInfo['details'] as List?;
      final detailsCount = infoDetails?.length ?? 0;
      developer.log('🔍 [$index] info.details 数量: $detailsCount', name: _tag);

      // 【简化】组合完整的睡眠数据（不包含 chronotype 相关字段）
      final combinedData = {
        ...cleanedDetails, // 包含 startDate, endDate, sleepTime, sleepEfficiency, score, type
        ...cleanedInfo, // 包含 totalTime, deepTime, lightTime, awakeTime, remTime, details, rawBytes
        'dailyValue': dailyValue,
        'deviceSn': getCurrentDeviceSn(),
      };

      developer.log(
          '🔍 [$index] 完整 JSON 数据: type=${combinedData['type']}, totalTime=${combinedData['totalTime']}, deepTime=${combinedData['deepTime']}, details数量=$detailsCount, dailyValue=$dailyValue',
          name: _tag);

      // 清除缓存，避免内存泄漏
      _sleepDetailsCache.remove(index);
      _sleepInfoCache.remove(index);

      // 上报睡眠数据
      _handleReportSleepDetailData(combinedData);
    } catch (e) {
      developer.log('❌ [$index] 组合睡眠数据失败: $e', name: _tag);
    }
  }

  /// 处理睡眠历史列表接收事件
  Future<void> _handleHistorySleepListReceived(dynamic arguments) async {
    // 【关键修复】防止重复查询
    if (_isQueryingSleepData) {
      developer.log('⚠️ 睡眠数据查询正在进行中，跳过重复触发', name: _tag);
      return;
    }

    Map<String, dynamic>? listMap;

    if (arguments is Map<String, dynamic>) {
      listMap = arguments;
    } else if (arguments is Map) {
      listMap = Map<String, dynamic>.from(arguments);
    }

    if (listMap != null && listMap.containsKey('dateList')) {
      final dateList = (listMap['dateList'] as List).cast<int>();
      developer.log('😴 收到睡眠历史列表: ${dateList.length} 条记录', name: _tag);
      developer.log('📋 时间戳列表: $dateList', name: _tag);

      // 调用验证接口
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备未连接，无法验证睡眠数据', name: _tag);
        return;
      }

      // 【关键修复】设置查询标志
      _isQueryingSleepData = true;

      try {
        // 调用验证接口
        final response =
            await DefaultApi().verifySleepDataGet<Map<String, dynamic>>(
          deviceSn: deviceSn,
          dateList: dateList,
        );

        if (response != null && response['code'] == 200) {
          final data = response['data'];
          if (data is List) {
            // 【关键修复】去重并排序索引列表
            final unReportedIndices = data.cast<int>().toSet().toList()..sort();
            developer.log('✅ 验证成功，未上报的索引（已去重）: $unReportedIndices', name: _tag);

            // 【关键修复】清空已查询索引记录，允许重新查询
            _queriedSleepIndices.clear();
            developer.log('🧹 清空已查询索引记录', name: _tag);

            // 【最终方案】顺序查询，等待每个索引上报完成后再查询下一个
            for (final index in unReportedIndices) {
              developer.log('🔄 [$index] 开始查询睡眠数据', name: _tag);

              // 【关键修复】清空当前索引的缓存，避免使用旧数据
              _sleepDetailsCache.remove(index);
              _sleepInfoCache.remove(index);

              // 设置当前查询的索引
              _currentQueryingIndex = index;

              // 创建一个 Completer 用于等待上报完成
              _sleepReportCompleter = Completer<void>();

              // 发起查询
              await _querySleepDataByIndex(index);

              // 等待上报完成（最多 5 秒超时）
              try {
                await _sleepReportCompleter!.future.timeout(
                  const Duration(seconds: 5),
                  onTimeout: () {
                    developer.log('⚠️ [$index] 等待上报超时（5秒），继续下一个', name: _tag);
                  },
                );
                developer.log('✅ [$index] 上报完成，继续下一个', name: _tag);
              } catch (e) {
                developer.log('❌ [$index] 等待上报异常: $e', name: _tag);
              }

              // 清理
              _sleepReportCompleter = null;
              _currentQueryingIndex = null;
            }

            developer.log('✅ 所有未上报索引查询完成', name: _tag);
          }
        } else {
          developer.log('❌ 验证失败: ${response?['msg']}', name: _tag);
        }
      } catch (e) {
        developer.log('❌ 验证睡眠数据失败: $e', name: _tag);
      } finally {
        // 【关键修复】清除查询标志
        _isQueryingSleepData = false;
      }
    }
  }

  /// 根据索引查询睡眠数据
  Future<void> _querySleepDataByIndex(int index) async {
    // 【关键修复】检查是否已查询过，避免重复查询
    if (_queriedSleepIndices.contains(index)) {
      developer.log('⚠️ 索引 $index 已查询过，跳过重复查询', name: _tag);
      return;
    }

    try {
      // 标记为已查询
      _queriedSleepIndices.add(index);

      await _methodChannel
          .invokeMethod('querySleepDataByIndex', {'index': index});
      developer.log('✅ 已发起索引 $index 的睡眠数据查询', name: _tag);
    } catch (e) {
      final errorMessage = e.toString();

      // 【关键修复】如果是查询锁冲突，等待后重试
      if (errorMessage.contains('QUERY_IN_PROGRESS')) {
        developer.log('⚠️ 索引 $index 查询冲突，等待 500ms 后重试', name: _tag);
        _queriedSleepIndices.remove(index); // 移除标记
        await Future.delayed(const Duration(milliseconds: 500));
        // 递归重试
        return _querySleepDataByIndex(index);
      }

      developer.log('❌ 查询索引 $index 的睡眠数据失败: $e', name: _tag);
      // 查询失败时移除标记，允许重试
      _queriedSleepIndices.remove(index);
    }
  }

  /// 处理睡眠类型接收事件（已废弃，不再使用）
  void _handleSleepChronotypeReceived(dynamic arguments) {
    // 【简化】不再处理 chronotype 数据
    developer.log('⚠️ 收到 chronotype 数据，但已不再使用', name: _tag);
  }

  /// 处理心率数据接收事件
  void _handleHeartRateReceived(dynamic arguments) {
    developer.log('❤️ 收到心率数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('heartRate')) {
      try {
        final heartRate = dataMap['heartRate'] as int;
        _heartRate.value = heartRate;
        developer.log('✅ 心率数据更新: $heartRate bpm', name: _tag);

        // 收到心率数据后，自动停止测量状态
        if (_isHeartRateMeasuring.value) {
          _isHeartRateMeasuring.value = false;
          developer.log('🔄 心率测量状态已自动停止', name: _tag);
        }

        // 立即上报心率数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty && heartRate > 0) {
          _autoReportSingleHeartRate(deviceSn, heartRate);
        }
      } catch (e) {
        developer.log('❌ 解析心率数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理实时心率数据接收事件
  void _handleRealtimeHeartRate(dynamic arguments) {
    developer.log('💓 收到实时心率数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('heartRate')) {
      try {
        final heartRate = dataMap['heartRate'] as int;
        _heartRate.value = heartRate;
        developer.log('✅ 实时心率数据更新: $heartRate bpm', name: _tag);

        // 收到实时心率数据后，自动停止测量状态
        if (_isHeartRateMeasuring.value) {
          _isHeartRateMeasuring.value = false;
          developer.log('🔄 心率测量状态已自动停止', name: _tag);
        }
      } catch (e) {
        developer.log('❌ 解析实时心率数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理电池电量接收事件
  void _handleBatteryReceived(dynamic arguments) {
    developer.log('🔋 收到电池数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    // 处理不同类型的Map，转换为 Map<String, dynamic>
    Map<String, dynamic>? batteryMap;

    if (arguments is Map<String, dynamic>) {
      batteryMap = arguments;
    } else if (arguments is Map) {
      batteryMap = Map<String, dynamic>.from(arguments);
      developer.log(
          '🔄 转换电池Map类型: ${arguments.runtimeType} -> Map<String, dynamic>',
          name: _tag);
    }

    if (batteryMap != null && batteryMap.containsKey('battery')) {
      try {
        final battery = batteryMap['battery'] as int;

        // 电池电量解析规则：
        // >100 表示充电中，后两位为实际电量
        // 例如：152 = 充电中 + 52%，101 = 充电中 + 1%，200 = 充电中 + 100%
        if (battery > 100) {
          _isCharging.value = true;
          final actualBattery = battery % 100;
          // 特殊处理：200 表示充电中且电量满（100%）
          _battery.value = actualBattery == 0 ? 100 : actualBattery;
          developer.log('✅ 电池电量更新: 充电中 ${_battery.value}%', name: _tag);
        } else {
          _battery.value = battery;
          _isCharging.value = false;
          developer.log('✅ 电池电量更新: $battery%', name: _tag);
        }
      } catch (e) {
        developer.log('❌ 解析电池电量失败: $e', name: _tag);
      }
    } else {
      developer.log('❌ 电池数据格式错误或缺少battery字段: $arguments', name: _tag);
    }
  }

  /// 处理血氧数据接收事件
  void _handleBloodOxygenReceived(dynamic arguments) {
    developer.log('🩸 收到血氧数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('bloodOxygen')) {
      try {
        final bloodOxygenData = BloodOxygenData.fromMap(dataMap);
        _bloodOxygenData.value = bloodOxygenData;
        developer.log('✅ 血氧数据更新: $bloodOxygenData', name: _tag);

        // 立即上报血氧数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty && bloodOxygenData.bloodOxygen > 0) {
          _autoReportSingleBloodOxygen(deviceSn, bloodOxygenData);
        }
      } catch (e) {
        developer.log('❌ 解析血氧数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理血氧历史数据接收事件
  void _handleHistoryBloodOxygenReceived(dynamic arguments) {
    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('bloodOxygenList')) {
      try {
        final historyBloodOxygenData = HistoryBloodOxygenData.fromMap(dataMap);
        _historyBloodOxygenData.value = historyBloodOxygenData;

        // 立即上报血氧历史数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty &&
            historyBloodOxygenData.bloodOxygenList.isNotEmpty) {
          _autoReportHistoryBloodOxygen(deviceSn, historyBloodOxygenData);
        }
      } catch (e) {
        developer.log('❌ 解析血氧历史数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理HRV数据接收事件
  void _handleHrvReceived(dynamic arguments) {
    developer.log('🫀 收到HRV数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('hrv')) {
      try {
        final hrvData = HrvData.fromMap(dataMap);
        _hrvData.value = hrvData;
        developer.log('✅ HRV数据更新: $hrvData', name: _tag);

        // 收到HRV数据后，自动停止测量状态
        if (_isHrvMeasuring.value) {
          _isHrvMeasuring.value = false;
          developer.log('🔄 HRV测量状态已自动停止', name: _tag);
        }

        // // 立即上报HRV数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty && hrvData.hrv > 0) {
          _autoReportSingleHrv(deviceSn, hrvData);
        }
      } catch (e) {
        developer.log('❌ 解析HRV数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理历史HRV数据接收事件
  void _handleHistoryHrvReceived(dynamic arguments) {
    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('hrvList')) {
      try {
        // 正确转换List<Object?>为List<int?>
        final rawList = dataMap['hrvList'] as List?;
        final hrvList = <int?>[];

        if (rawList != null) {
          for (var item in rawList) {
            if (item == null) {
              hrvList.add(null);
            } else if (item is int) {
              hrvList.add(item);
            } else {
              hrvList.add(int.tryParse(item.toString()));
            }
          }
        }

        // 保存历史HRV列表
        _historyHrvList.value = hrvList;

        final timeInterval = dataMap['timeInterval'] ?? 5;
        final historyDay = dataMap['historyDay'] ?? 'TODAY';

        // 立即上报HRV列表数据（即使为空也要缓存，确保能触发上报）
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty) {
          _autoReportHrvList(deviceSn, hrvList, timeInterval, historyDay);
        }
      } catch (e) {
        developer.log('❌ 解析历史HRV数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理压力数据接收事件
  void _handleStressReceived(dynamic arguments) {
    developer.log('😰 收到压力数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('stress')) {
      try {
        final stressData = StressData.fromMap(dataMap);
        _stressData.value = stressData;
        developer.log('✅ 压力数据更新: $stressData', name: _tag);

        // 注意：单个压力值不上报，只上报压力列表（在 _handleStressListReceived 中）
        // 避免重复上报
      } catch (e) {
        developer.log('❌ 解析压力数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理压力列表数据接收事件
  Future<void> _handleStressListReceived(dynamic arguments) async {
    try {
      List<int?> stressList = [];
      String? historyDay;

      // 处理不同类型的Map，转换为统一格式
      Map<String, dynamic>? stressMap;
      if (arguments is Map<String, dynamic>) {
        stressMap = arguments;
      } else if (arguments is Map) {
        stressMap = Map<String, dynamic>.from(arguments);
      }

      if (stressMap != null && stressMap.containsKey('stressList')) {
        final listData = stressMap['stressList'];
        historyDay = stressMap['historyDay'] as String?;

        if (listData is List) {
          // 转换列表，保留null值
          stressList = listData
              .map((e) => e == null
                  ? null
                  : (e is int ? e : int.tryParse(e.toString()) ?? 0))
              .toList();
        }
      } else if (arguments is List) {
        stressList = arguments
            .map((e) => e == null
                ? null
                : (e is int ? e : int.tryParse(e.toString()) ?? 0))
            .toList();
      }

      // 只更新今天的数据到UI
      if (historyDay == null || historyDay == 'TODAY') {
        _todayStressList.value = stressList;
        _todayStressList.refresh();
      }

      // 立即上报压力列表数据（带历史日期）
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isNotEmpty && stressList.isNotEmpty) {
        _autoReportStressList(deviceSn, stressList,
            historyDayString: historyDay);
      }
    } catch (e) {
      developer.log('❌ 解析压力列表数据失败: $e', name: _tag);
    }
  }

  /// 处理血压数据接收事件
  void _handleBloodPressureReceived(dynamic arguments) {
    developer.log('🩺 收到血压数据: $arguments (类型: ${arguments.runtimeType})',
        name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null &&
        dataMap.containsKey('systolic') &&
        dataMap.containsKey('diastolic')) {
      try {
        final systolic = dataMap['systolic'] as int;
        final diastolic = dataMap['diastolic'] as int;
        developer.log('✅ 血压数据更新: 收缩压=${systolic}mmHg, 舒张压=${diastolic}mmHg',
            name: _tag);
        // 可以创建一个血压数据模型来存储这些数据
      } catch (e) {
        developer.log('❌ 解析血压数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理固件版本接收事件
  void _handleFirmwareVersionReceived(dynamic arguments) {
    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('version')) {
      try {
        final version = dataMap['version'] as String?;
        developer.log('✅ 固件版本: $version', name: _tag);

        // 获取固件版本后，立即调用 addMyInfoPost 接口上报设备信息
        if (version != null && version.isNotEmpty) {
          _reportDeviceInfo(version);
        }
      } catch (e) {
        developer.log('❌ 解析固件版本失败: $e', name: _tag);
      }
    }
  }

  /// 将颜色代码转换为文字描述
  String? _convertColorCodeToText(String? colorCode) {
    if (colorCode == null) return '未知颜色';

    // 根据颜色代码返回对应的文字描述
    switch (colorCode) {
      case '0':
        return '典雅黑';
      case '2':
        return '奢雅金';
      case '3':
        return '玫瑰金';
      default:
        return '未知颜色';
    }
  }

  /// 上报设备信息到服务器
  Future<void> _reportDeviceInfo(String firmwareVersion) async {
    try {
      developer.log('📤 开始上报设备信息到服务器', name: _tag);

      // 获取当前连接的设备
      final device = _connectedDevice.value;
      if (device == null) {
        developer.log('❌ 当前没有连接的设备，无法上报设备信息', name: _tag);
        return;
      }

      // 从 scanRecord 中提取设备信息
      final deviceSn = device.deviceSn;
      final deviceName = device.name;
      final macAddress = device.address;
      final deviceColorCode = device.deviceColor; // 从 scanRecord 解析的颜色代码
      final deviceColor = _convertColorCodeToText(deviceColorCode); // 转换为文字
      final deviceSize = device.deviceSize; // 从 scanRecord 解析
      final chipId = device.chipId; // 从 scanRecord 解析

      developer.log(
          '📋 设备信息: deviceSn=$deviceSn, name=$deviceName, version=$firmwareVersion, '
          'colorCode=$deviceColorCode, color=$deviceColor, size=$deviceSize, chipId=$chipId, mac=$macAddress',
          name: _tag);

      // 调用 addMyInfoPost 接口
      final response = await DefaultApi().addMyInfoPost<Map<String, dynamic>>(
        deviceSn: deviceSn,
        deviceName: deviceName,
        deviceColor: deviceColor,
        deviceSize: deviceSize,
        versionNumber: firmwareVersion,
        macAddress: macAddress,
        serialNumber: chipId,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (response != null) {
        developer.log('✅ 设备信息上报成功: $response', name: _tag);
      } else {
        developer.log('⚠️ 设备信息上报失败或无响应', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 上报设备信息异常: $e', name: _tag);
    }
  }

  /// 解析连接状态字符串
  RingConnectionState _parseConnectionState(String stateString) {
    switch (stateString) {
      case 'connected':
        return RingConnectionState.connected;
      case 'connecting':
        return RingConnectionState.connecting;
      case 'disconnected':
        return RingConnectionState.disconnected;
      default:
        return RingConnectionState.disconnected;
    }
  }

  /// 连接成功后自动绑定设备并上报数据
  Future<void> _handleConnectionSuccess() async {
    print('🎯🎯🎯 [RingService] 连接成功事件触发！开始处理...');
    developer.log('🎯 开始处理连接成功事件', name: _tag);

    try {
      if (_isInitializingDevice.value) {
        print('⚠️ [RingService] 设备正在初始化中，跳过重复处理');
        developer.log('⚠️ 设备正在初始化中，跳过重复处理', name: _tag);
        return;
      }

      // 如果已经在数据同步中，也跳过
      if (_isDataSyncing.value) {
        print('⚠️ [RingService] 数据正在同步中，跳过重复处理');
        developer.log('⚠️ 数据正在同步中，跳过重复处理', name: _tag);
        return;
      }

      _isInitializingDevice.value = true;
      _isDataSyncing.value = true; // 开始数据同步

      _clearReportedDataMarks();

      // 【新增】启动超时检查，15秒后强制上报已收集的数据
      _startMultiDayDataTimeoutCheck();

      final deviceSn = getCurrentDeviceSn();
      print('📱 [RingService] 当前设备SN: $deviceSn');

      if (deviceSn.isEmpty) {
        print('❌ [RingService] 设备SN为空，终止处理');
        _isInitializingDevice.value = false;
        return;
      }

      try {
        final deviceSnManager = Get.find<DeviceSnManager>();
        await deviceSnManager.saveDeviceSn(deviceSn);
        print('💾 [RingService] 设备SN已保存');
        developer.log('💾 设备SN已保存到DeviceSnManager', name: _tag);
      } catch (e) {
        print('⚠️ [RingService] 保存设备SN失败: $e');
        developer.log('⚠️ 保存设备SN失败: $e', name: _tag);
      }

      // 1. 绑定设备到服务器
      print('🔗 [RingService] 第一步：绑定设备到服务器');
      developer.log('🔗 第一步：绑定设备到服务器', name: _tag);

      try {
        final bindSuccess = await _bindDevice(deviceSn);
        if (!bindSuccess) {
          print('❌ [RingService] 设备绑定失败，跳过后续操作');
          developer.log('❌ 设备绑定失败，跳过后续操作', name: _tag);
          _isInitializingDevice.value = false;
          return;
        }
        print('✅ [RingService] 设备绑定成功');
      } catch (e) {
        print('❌ [RingService] 设备绑定异常: $e');
        print('❌ [RingService] 堆栈: ${e.toString()}');
        _isInitializingDevice.value = false;
        return;
      }

      // 2. 查询所有设备数据
      print('📊 [RingService] 第二步：查询所有设备数据');
      developer.log('📊 第二步：查询所有设备数据', name: _tag);
      _completedSyncSteps.value = 0; // 重置进度
      _totalSyncSteps.value = 7; // 总共7个步骤

      // 3. 【顺序查询】按照优先级顺序查询数据，确保数据完整性
      developer.log('📊 开始顺序查询设备数据', name: _tag);

      // 步骤1: 查询步数数据（查询今天到7天前）
      try {
        await queryCurrentSteps(); // 查询今天
        // 查询过去7天的步数数据（包括详细步数）
        for (int i = 1; i <= 7; i++) {
          final historyDay = i == 1 ? 'YESTERDAY' : 'DAYS_AGO_$i';
          await queryStepsForDate(historyDay);
          await Future.delayed(const Duration(milliseconds: 100)); // 避免请求过快
        }
        developer.log('✅ 步数数据查询完成（今天到7天前）', name: _tag);
      } catch (e) {
        developer.log('❌ 步数查询异常: $e', name: _tag);
      }

      // 等待步数数据收集完成（最多5秒）
      await _waitForDataCollection('sport', 5);

      // 等待运动明细数据收集完成（最多5秒）
      await _waitForDataCollection('sportDetail', 5);

      // 步骤2: 查询心率数据（会自动查询8天）
      try {
        await queryHeartRate();
        developer.log('✅ 心率数据查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ 心率查询异常: $e', name: _tag);
      }

      // 等待心率数据收集完成（最多5秒）
      await _waitForDataCollection('heartRate', 5);

      // 步骤3: 查询HRV数据（会自动查询8天）
      try {
        await queryHrv();
        developer.log('✅ HRV数据查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ HRV查询异常: $e', name: _tag);
      }

      // 等待HRV数据收集完成（最多5秒）
      await _waitForDataCollection('hrv', 5);

      // 步骤4: 查询压力数据（会自动查询8天）
      try {
        await queryTodayStressList();
        developer.log('✅ 压力数据查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ 压力查询异常: $e', name: _tag);
      }

      // 等待压力数据收集完成（最多5秒）
      await _waitForDataCollection('stress', 5);

      // 步骤5: 查询血氧数据（会自动查询8天）
      try {
        await queryBloodOxygen();
        developer.log('✅ 血氧数据查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ 血氧查询异常: $e', name: _tag);
      }

      // 等待血氧数据收集完成（最多5秒）
      await _waitForDataCollection('bloodOxygen', 5);

      // 步骤6: 查询运动详情（会自动查询8天）
      try {
        await queryExerciseDetails();
        developer.log('✅ 运动详情查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ 运动详情查询异常: $e', name: _tag);
      }

      // 等待活动详情数据收集完成（最多5秒）
      await _waitForDataCollection('event', 5);

      // 步骤7: 查询电池电量
      try {
        await queryBattery();
        developer.log('✅ 电池电量查询完成', name: _tag);
      } catch (e) {
        developer.log('❌ 电池查询异常: $e', name: _tag);
      }

      developer.log('✅ 所有设备数据查询完成', name: _tag);

      // 【关键修复】先等待5秒，给设备足够时间返回数据
      // 这在release模式下特别重要，因为代码执行速度更快
      print('⏳ [RingService] 等待5秒，让设备有时间返回数据...');
      developer.log('⏳ 等待5秒，让设备有时间返回数据（release模式优化）', name: _tag);
      await Future.delayed(const Duration(seconds: 5));
      print('✅ [RingService] 初始等待完成，开始检查数据上报状态');

      // 等待数据上报完成（最多30秒）
      // 注意：这里不是固定等待，而是等待所有数据回调并上报完成
      developer.log('⏳ 开始等待数据回调和上报完成（最多30秒）...', name: _tag);
      final maxWaitTime = DateTime.now().add(const Duration(seconds: 30));
      int lastCount = -1;
      int stableCount = 0;
      int noChangeCount = 0;

      while (DateTime.now().isBefore(maxWaitTime)) {
        // 如果计数器稳定在0超过3秒，认为所有数据已上报完成
        if (_pendingReportCount.value == 0) {
          if (lastCount == 0) {
            stableCount++;
            if (stableCount >= 6) {
              // 6次检查 * 500ms = 3秒稳定
              developer.log('✅ 计数器稳定在0，所有数据已上报完成', name: _tag);
              break;
            }
          } else {
            stableCount = 1;
          }
        } else {
          stableCount = 0;

          // 如果计数器长时间不变化（可能设备没有返回某些数据），也继续
          if (lastCount == _pendingReportCount.value) {
            noChangeCount++;
            if (noChangeCount >= 20) {
              // 20次检查 * 500ms = 10秒无变化
              developer.log('⚠️ 计数器10秒无变化，可能部分数据未返回，继续后续流程', name: _tag);
              break;
            }
          } else {
            noChangeCount = 0;
          }

          developer.log('⏳ 等待数据上报完成，剩余: ${_pendingReportCount.value}',
              name: _tag);
        }

        lastCount = _pendingReportCount.value;
        await Future.delayed(const Duration(milliseconds: 500));
      }

      if (_pendingReportCount.value > 0) {
        developer.log(
            '⚠️ 等待超时或部分数据未返回，仍有 ${_pendingReportCount.value} 个数据未上报完成',
            name: _tag);
      } else {
        developer.log('✅ 所有数据已上报完成', name: _tag);
      }

      // 【关键】标记数据上报完成，通知外部可以查询详情数据
      _dataReportCompleted.value = true;
      developer.log('🎉 数据上报完成标志已设置，外部可以安全查询详情数据', name: _tag);

      // 4. 检查哪些数据没有收到，手动查询
      developer.log('🔍 第四步：检查并补充缺失的数据', name: _tag);
      await _checkAndFetchMissingData();

      // 再次等待补充数据的上报完成
      if (_pendingReportCount.value > 0) {
        developer.log('⏳ 等待补充数据上报完成...', name: _tag);
        final additionalWaitTime =
            DateTime.now().add(const Duration(seconds: 5));
        while (_pendingReportCount.value > 0 &&
            DateTime.now().isBefore(additionalWaitTime)) {
          developer.log('⏳ 等待补充数据上报，剩余: ${_pendingReportCount.value}',
              name: _tag);
          await Future.delayed(const Duration(milliseconds: 500));
        }
      }
    } catch (e) {
      developer.log('处理连接成功事件异常: $e', name: _tag);
    } finally {
      _isInitializingDevice.value = false;
    }
  }

  /// 检查并获取缺失的数据
  Future<void> _checkAndFetchMissingData() async {
    try {
      developer.log('🔍 开始检查缺失的数据', name: _tag);

      // 检查运动记录
      if (_sportRecord.value == null || _sportRecord.value!.steps == 0) {
        developer.log('⚠️ 运动记录数据缺失，手动查询', name: _tag);
        await queryExerciseDetails();
        await Future.delayed(const Duration(milliseconds: 500));
      } else {
        developer.log('✅ 运动记录数据已存在: ${_sportRecord.value}', name: _tag);
      }

      // 检查心率列表
      if (_historyHeartRateData.value == null ||
          _historyHeartRateData.value!.heartRateList.isEmpty) {
        developer.log('⚠️ 心率列表数据缺失，手动查询', name: _tag);
        await queryHeartRate();
        await Future.delayed(const Duration(milliseconds: 500));
      } else {
        developer.log(
            '✅ 心率列表数据已存在: ${_historyHeartRateData.value!.heartRateList.length} 个数据点',
            name: _tag);
      }

      // 检查HRV列表数据（添加详细日志)
      developer.log(
          '🔍 检查HRV数据状态: _historyHrvList.value=${_historyHrvList.value}, isEmpty=${_historyHrvList.value?.isEmpty ?? true}',
          name: _tag);
      if (_historyHrvList.value == null || _historyHrvList.value!.isEmpty) {
        developer.log('⚠️ HRV列表数据缺失，手动查询', name: _tag);
        await queryHrv();
        await Future.delayed(const Duration(milliseconds: 500));
      } else {
        developer.log('✅ HRV列表数据已存在: ${_historyHrvList.value!.length} 个数据点',
            name: _tag);
      }

      // 检查压力列表
      if (_todayStressList.isEmpty) {
        developer.log('⚠️ 压力列表数据缺失，手动查询', name: _tag);
        await queryTodayStressList();
        await Future.delayed(const Duration(milliseconds: 500));
      } else {
        developer.log('✅ 压力列表数据已存在: ${_todayStressList.length} 个数据点',
            name: _tag);
      }

      developer.log('✅ 缺失数据检查完成', name: _tag);
    } catch (e) {
      developer.log('❌ 检查缺失数据异常: $e', name: _tag);
    }
  }

  // ==================== 单独上报方法（收到一种数据立即上报一种） ====================

  /// 检查数据是否已上报（防止重复上报）
  bool _isDataReported(String dataType, String identifier) {
    final key = '$dataType:$identifier';
    return _reportedDataKeys.contains(key);
  }

  /// 标记数据已上报
  void _markDataAsReported(String dataType, String identifier) {
    final key = '$dataType:$identifier';
    _reportedDataKeys.add(key);
    developer.log('🔖 标记数据已上报: $key', name: _tag);
  }

  /// 清除上报标记（用于重新连接或切换设备时）
  void _clearReportedDataMarks() {
    _reportedDataKeys.clear();
    _pendingReportCount.value = 0;
    _allDataReported.value = false;
    _dataReportCompleted.value = false; // 重置数据上报完成标志
    final oldProgress = _syncProgress.value;
    _syncProgress.value = 0;
    _completedSyncSteps.value = 0;
    _hrvReportCompleted.value = false; // 重置HRV上报标志
    _pendingReportQueue.clear(); // 清空待上报队列

    // 【新增】清除睡眠数据相关缓存
    _sleepDetailsCache.clear();
    _sleepInfoCache.clear();
    _queriedSleepIndices.clear(); // 清除已查询索引记录
    _currentQueryingIndex = null;
    _sleepReportCompleter = null;
    _isQueryingSleepData = false; // 清除查询标志

    // 【新增】清除多天数据缓存
    _multiDayHeartRateData.clear();
    _multiDayHrvData.clear();
    _multiDayStressData.clear();
    _multiDayBloodOxygenData.clear();
    _multiDayEventData.clear();
    _multiDaySportData.clear();
    _multiDaySportDetailData.clear();
    _multiDaySportDetailData.clear();

    developer.log('🧹 清除所有上报标记和计数器（进度从 $oldProgress% 重置为 0%）', name: _tag);
    print('🧹 [RingService] 清除进度：$oldProgress% → 0%');
  }

  /// 启动多天数据超时检查（15秒后强制上报已收集的数据）
  void _startMultiDayDataTimeoutCheck() {
    developer.log('⏰ 启动多天数据超时检查（15秒）', name: _tag);

    Future.delayed(const Duration(seconds: 15), () async {
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isEmpty) return;

      developer.log('⏰ 超时检查触发，开始强制上报已收集的数据', name: _tag);

      // 强制上报心率数据
      if (_multiDayHeartRateData.isNotEmpty) {
        developer.log('⏰ 强制上报心率数据（已收集${_multiDayHeartRateData.length}天）',
            name: _tag);
        await _reportMultiDayHeartRate(deviceSn, _cachedTimeInterval);
      }

      // 强制上报HRV数据
      if (_multiDayHrvData.isNotEmpty) {
        developer.log('⏰ 强制上报HRV数据（已收集${_multiDayHrvData.length}天）',
            name: _tag);
        await _reportMultiDayHrv(deviceSn, _cachedTimeInterval);
      }

      // 强制上报压力数据
      if (_multiDayStressData.isNotEmpty) {
        developer.log('⏰ 强制上报压力数据（已收集${_multiDayStressData.length}天）',
            name: _tag);
        await _reportMultiDayStress(deviceSn);
      }

      // 强制上报血氧数据
      if (_multiDayBloodOxygenData.isNotEmpty) {
        developer.log('⏰ 强制上报血氧数据（已收集${_multiDayBloodOxygenData.length}天）',
            name: _tag);
        await _reportMultiDayBloodOxygen(deviceSn, _cachedTimeInterval);
      }

      // 强制上报活动详情数据
      if (_multiDayEventData.isNotEmpty) {
        developer.log('⏰ 强制上报活动详情数据（已收集${_multiDayEventData.length}天）',
            name: _tag);
        await _reportMultiDayEvent();
      }

      // 强制上报运动记录数据
      if (_multiDaySportData.isNotEmpty) {
        developer.log('⏰ 强制上报运动记录数据（已收集${_multiDaySportData.length}天）',
            name: _tag);
        await _reportMultiDaySport(deviceSn);
      }

      // 强制上报运动明细数据
      if (_multiDaySportDetailData.isNotEmpty) {
        developer.log('⏰ 强制上报运动明细数据（已收集${_multiDaySportDetailData.length}天）',
            name: _tag);
        await _reportMultiDaySportDetail();
      }

      developer.log('✅ 超时检查完成，所有已收集数据已上报', name: _tag);
    });
  }

  /// 等待特定类型的数据收集完成
  Future<void> _waitForDataCollection(String dataType, int maxSeconds) async {
    developer.log('⏳ 等待 $dataType 数据收集完成（最多${maxSeconds}秒）', name: _tag);

    final startTime = DateTime.now();
    int lastCount = -1;
    int stableCount = 0;

    while (DateTime.now().difference(startTime).inSeconds < maxSeconds) {
      int currentCount = 0;

      switch (dataType) {
        case 'heartRate':
          currentCount = _multiDayHeartRateData.length;
          break;
        case 'hrv':
          currentCount = _multiDayHrvData.length;
          break;
        case 'stress':
          currentCount = _multiDayStressData.length;
          break;
        case 'bloodOxygen':
          currentCount = _multiDayBloodOxygenData.length;
          break;
        case 'event':
          currentCount = _multiDayEventData.length;
          break;
        case 'sport':
          currentCount = _multiDaySportData.length;
          break;
        case 'sportDetail':
          currentCount = _multiDaySportDetailData.length;
          break;
      }

      // 如果数据量稳定（连续3次检查都相同），认为收集完成
      if (currentCount == lastCount) {
        stableCount++;
        if (stableCount >= 3) {
          developer.log('✅ $dataType 数据收集完成（已收集${currentCount}天）', name: _tag);
          return;
        }
      } else {
        stableCount = 0;
      }

      lastCount = currentCount;
      await Future.delayed(const Duration(milliseconds: 500));
    }

    developer.log('⏰ $dataType 数据收集超时（已收集${lastCount}天）', name: _tag);
  }

  /// 更新同步进度（HRV已经是1/7，其他数据从2开始）
  void _updateSyncProgress(String stepName) {
    // HRV数据不在这里处理，已经在 _autoReportHrvList 中设置为 1/7
    if (stepName == 'HRV数据') {
      developer.log('⚠️ HRV数据进度已单独处理，跳过', name: _tag);
      return; // HRV数据已经单独处理
    }

    // 其他数据：确保从2开始
    if (_completedSyncSteps.value < 1) {
      _completedSyncSteps.value = 1; // 至少从1开始（HRV占用了1）
      developer.log('⚠️ 进度步骤小于1，重置为1（HRV占位）', name: _tag);
    }
    _completedSyncSteps.value++;

    final oldProgress = _syncProgress.value;
    _syncProgress.value =
        ((_completedSyncSteps.value / _totalSyncSteps.value) * 100).round();
    developer.log(
        '📊 同步进度更新: $stepName 完成 (${_completedSyncSteps.value}/${_totalSyncSteps.value}) - ${oldProgress}% → ${_syncProgress.value}%',
        name: _tag);

    // 检查是否完成所有步骤
    if (_completedSyncSteps.value >= _totalSyncSteps.value) {
      developer.log('🎉 所有同步步骤已完成！', name: _tag);
    }
  }

  /// 增加待上报数据计数
  void _incrementPendingReport() {
    _pendingReportCount.value++;
    _allDataReported.value = false;
    developer.log('📊 待上报数据 +1，当前: ${_pendingReportCount.value}', name: _tag);
  }

  /// 减少待上报数据计数
  void _decrementPendingReport() {
    if (_pendingReportCount.value > 0) {
      _pendingReportCount.value--;
      developer.log('📊 待上报数据 -1，剩余: ${_pendingReportCount.value}', name: _tag);

      // 如果所有数据都已上报完成，只标记状态，不自动触发获取
      if (_pendingReportCount.value == 0) {
        _allDataReported.value = true;
        developer.log('✅ 所有数据上报完成', name: _tag);
      }
    }
  }

  /// 批量上报多天运动明细数据
  Future<void> _reportMultiDaySportDetail() async {
    if (_multiDaySportDetailData.isEmpty) {
      developer.log('⚠️ 没有运动明细数据需要上报', name: _tag);
      return;
    }

    _incrementPendingReport();
    try {
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备未连接，无法上报运动明细', name: _tag);
        return;
      }

      final reportKey = '$deviceSn:multiday_sport_detail';
      if (_isDataReported('sportDetail', reportKey)) {
        developer.log('⚠️ 多天运动明细数据已上报，跳过重复上报', name: _tag);
        return;
      }

      developer.log('📤 批量上报运动明细数据: ${_multiDaySportDetailData.length}天',
          name: _tag);

      final sportDetailList = <Map<String, dynamic>>[];
      for (var entry in _multiDaySportDetailData.entries) {
        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        sportDetailList.add({
          'list': entry.value.isEmpty ? null : entry.value, // 如果列表为空，设置为 null
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
        });
      }

      // 构建批量上报数据
      final batchData = {
        'deviceSn': deviceSn,
        'stress': sportDetailList,
      };

      // 批量上报所有天的数据
      await DefaultApi().addSportDetailPost<dynamic>(
        batchData: batchData,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      _markDataAsReported('sportDetail', reportKey);
      _multiDaySportDetailData.clear();
      developer.log('✅ 运动明细数据批量上报成功', name: _tag);
      _updateSyncProgress('运动明细');
    } catch (e) {
      developer.log('❌ 运动明细数据批量上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 单独上报步数详情数据（已废弃，改用批量上报）
  @Deprecated('使用 _reportMultiDaySportDetail 代替')
  Future<void> _autoReportStepsDetailData(
      String deviceSn, List<int?> stepsList) async {
    // 【修复】移除HRV依赖，直接上报数据
    _incrementPendingReport(); // 开始上报，计数+1
    try {
      final now = DateTime.now();
      final historyDay =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      // 检查是否已上报
      if (_isDataReported('sportDetail', '$deviceSn:$historyDay')) {
        developer.log('⚠️ 步数详情数据已上报，跳过重复上报', name: _tag);
        return;
      }

      developer.log('📤 单独上报步数详情数据', name: _tag);

      // 过滤掉null值，转换为List<int>
      final validStepsList = stepsList.whereType<int>().toList();

      // 获取设备SN
      final currentDeviceSn = getCurrentDeviceSn();
      if (currentDeviceSn.isEmpty) {
        developer.log('⚠️ 设备SN为空，跳过步数详情上报', name: _tag);
        return;
      }

      final sportDetail = RingSportDetail.fromStepsData(
        deviceSn: currentDeviceSn,
        historyDay: historyDay,
        stepsList: validStepsList,
      );

      await DefaultApi().addSportDetailPost<dynamic>(
        sportDetail: sportDetail,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      // 标记已上报
      _markDataAsReported('sportDetail', '$deviceSn:$historyDay');
      developer.log('✅ 步数详情数据上报成功', name: _tag);
      _updateSyncProgress('步数详情');
    } catch (e) {
      developer.log('❌ 步数详情数据上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport(); // 上报完成（无论成功或失败），计数-1
    }
  }

  /// 单独上报单次心率数据
  Future<void> _autoReportSingleHeartRate(
      String deviceSn, int heartRate) async {
    try {
      developer.log('📤 单独上报心率数据: $heartRate BPM', name: _tag);

      final now = DateTime.now();
      final dailyValue =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      await DefaultApi().addHeartRatePost<dynamic>(
        heartRate: heartRate.toString(),
        deviceSn: deviceSn,
        dailyValue: dailyValue,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      developer.log('✅ 心率数据上报成功', name: _tag);
    } catch (e) {
      developer.log('❌ 心率数据上报失败: $e', name: _tag);
    }
  }

  /// 单独上报历史心率数据（收集多天数据）
  Future<void> _autoReportHistoryHeartRate(
      String deviceSn, HistoryHeartRateData data) async {
    try {
      final historyDayString = data.historyDay;

      // 缓存 timeInterval
      _cachedTimeInterval = data.timeInterval;

      // 缓存数据（只缓存有数据的天数）
      if (data.heartRateList.isNotEmpty) {
        _multiDayHeartRateData[historyDayString] = data.heartRateList;
      }

      // 只在收到 DAYS_AGO_7 时触发上报，确保所有8天数据都查询完毕
      if (historyDayString == 'DAYS_AGO_7') {
        developer.log('📤 心率数据收集完成（${_multiDayHeartRateData.length}天有效数据），开始上报',
            name: _tag);
        await _reportMultiDayHeartRate(deviceSn, data.timeInterval);
      }
    } catch (e) {
      developer.log('❌ 缓存心率数据失败: $e', name: _tag);
    }
  }

  /// 上报多天心率数据
  Future<void> _reportMultiDayHeartRate(
      String deviceSn, int timeInterval) async {
    // 检查是否已上报
    final reportKey = '$deviceSn:multiday_heartrate';
    if (_isDataReported('heartRateInfo', reportKey)) {
      developer.log('⚠️ 多天心率数据已上报，跳过重复上报', name: _tag);
      return;
    }

    if (_multiDayHeartRateData.isEmpty) {
      developer.log('⚠️ 心率数据缓存为空，跳过上报', name: _tag);
      return;
    }

    _incrementPendingReport();
    try {
      // 构建多天数据
      final heartRateData = <Map<String, dynamic>>[];
      for (var entry in _multiDayHeartRateData.entries) {
        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        heartRateData.add({
          'list': entry.value,
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
          'timeInterval': timeInterval, // 添加 timeInterval 参数
        });
      }

      await DefaultApi().addHeartRateInfoPost<dynamic>(
        deviceSn: deviceSn,
        heartRate: heartRateData,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      // 标记已上报并清空缓存
      _markDataAsReported('heartRateInfo', reportKey);
      _multiDayHeartRateData.clear();
      developer.log(
          '✅ 心率数据上报成功（${heartRateData.length}天，timeInterval=$timeInterval）',
          name: _tag);
      _updateSyncProgress('心率数据');
    } catch (e) {
      developer.log('❌ 心率数据上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 格式化日期为服务器要求的格式（RFC 1123）
  /// 格式: EEE MMM dd HH:mm:ss zzz yyyy
  /// 例如: Mon Oct 13 15:23:14 GMT+08:00 2025
  String _formatDateTimeForApi(DateTime dateTime) {
    // 注意：Dart 的 HttpDate.format 生成的是 UTC 时间
    // 我们需要保留本地时区，所以手动格式化
    final weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    final months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];

    final weekday = weekdays[dateTime.weekday - 1];
    final month = months[dateTime.month - 1];
    final day = dateTime.day.toString().padLeft(2, '0');
    final hour = dateTime.hour.toString().padLeft(2, '0');
    final minute = dateTime.minute.toString().padLeft(2, '0');
    final second = dateTime.second.toString().padLeft(2, '0');
    final year = dateTime.year;

    // 获取时区偏移
    final offset = dateTime.timeZoneOffset;
    final offsetHours = offset.inHours.abs().toString().padLeft(2, '0');
    final offsetMinutes =
        (offset.inMinutes.abs() % 60).toString().padLeft(2, '0');
    final offsetSign = offset.isNegative ? '-' : '+';
    final timezone = 'GMT$offsetSign$offsetHours:$offsetMinutes';

    return '$weekday $month $day $hour:$minute:$second $timezone $year';
  }

  /// 单独上报血氧数据
  Future<void> _autoReportSingleBloodOxygen(
      String deviceSn, BloodOxygenData data) async {
    try {
      developer.log('📤 单独上报血氧数据: ${data.bloodOxygen}%', name: _tag);

      await DefaultApi().addBloodOxygenDetailPost<dynamic>(
        bloodOxygen: data.bloodOxygen.toString(),
        deviceSn: deviceSn,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      developer.log('✅ 血氧数据上报成功', name: _tag);
    } catch (e) {
      developer.log('❌ 血氧数据上报失败: $e', name: _tag);
    }
  }

  /// 单独上报血氧历史数据（收集多天数据）
  Future<void> _autoReportHistoryBloodOxygen(
      String deviceSn, HistoryBloodOxygenData data) async {
    try {
      final historyDayString = data.historyDay;

      // 缓存 timeInterval
      _cachedTimeInterval = data.timeInterval;

      // 缓存数据（只缓存有数据的天数）
      if (data.bloodOxygenList.isNotEmpty) {
        _multiDayBloodOxygenData[historyDayString] = data.bloodOxygenList;
      }

      // 只在收到 DAYS_AGO_7 时触发上报
      if (historyDayString == 'DAYS_AGO_7') {
        developer.log(
            '📤 血氧数据收集完成（${_multiDayBloodOxygenData.length}天有效数据），开始上报',
            name: _tag);
        await _reportMultiDayBloodOxygen(deviceSn, data.timeInterval);
      }
    } catch (e) {
      developer.log('❌ 缓存血氧数据失败: $e', name: _tag);
    }
  }

  /// 上报多天血氧数据
  Future<void> _reportMultiDayBloodOxygen(
      String deviceSn, int timeInterval) async {
    final reportKey = '$deviceSn:multiday_bloodoxygen';
    if (_isDataReported('bloodOxygenDetail', reportKey)) {
      developer.log('⚠️ 多天血氧数据已上报，跳过重复上报', name: _tag);
      return;
    }

    if (_multiDayBloodOxygenData.isEmpty) {
      developer.log('⚠️ 血氧数据缓存为空，跳过上报', name: _tag);
      return;
    }

    _incrementPendingReport();
    try {
      final bloodOxygenData = <Map<String, dynamic>>[];
      for (var entry in _multiDayBloodOxygenData.entries) {
        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        bloodOxygenData.add({
          'list': entry.value,
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
          'timeInterval': timeInterval, // 添加 timeInterval 参数
        });
      }

      await DefaultApi().addBloodOxygenPost<dynamic>(
        deviceSn: deviceSn,
        bloodOxygen: bloodOxygenData,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      _markDataAsReported('bloodOxygenDetail', reportKey);
      _multiDayBloodOxygenData.clear();
      developer.log(
          '✅ 血氧数据上报成功（${bloodOxygenData.length}天，timeInterval=$timeInterval）',
          name: _tag);
      _updateSyncProgress('血氧数据');
    } catch (e) {
      developer.log('❌ 血氧数据上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 单独上报HRV数据
  Future<void> _autoReportSingleHrv(String deviceSn, HrvData data) async {
    try {
      final now = DateTime.now();
      final dailyValue =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      await DefaultApi().addHrvPost<dynamic>(
        hrv: data.hrv.toString(),
        deviceSn: deviceSn,
        dailyValue: dailyValue,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      developer.log('✅ HRV数据上报成功', name: _tag);
    } catch (e) {
      developer.log('❌ HRV数据上报失败: $e', name: _tag);
    }
  }

  /// 单独上报压力列表数据（收集多天数据）
  Future<void> _autoReportStressList(String deviceSn, List<int?> stressList,
      {String? historyDayString}) async {
    try {
      final historyDay = historyDayString ?? 'TODAY';

      // 缓存数据（只缓存有数据的天数）
      if (stressList.isNotEmpty) {
        _multiDayStressData[historyDay] = stressList;
      }

      // 只在收到 DAYS_AGO_7 时触发上报
      if (historyDay == 'DAYS_AGO_7') {
        developer.log('📤 压力数据收集完成（${_multiDayStressData.length}天有效数据），开始上报',
            name: _tag);
        await _reportMultiDayStress(deviceSn);
      }
    } catch (e) {
      developer.log('❌ 缓存压力数据失败: $e', name: _tag);
    }
  }

  /// 上报多天压力数据
  Future<void> _reportMultiDayStress(String deviceSn) async {
    final reportKey = '$deviceSn:multiday_stress';
    if (_isDataReported('stressChangeInfo', reportKey)) {
      developer.log('⚠️ 多天压力数据已上报，跳过重复上报', name: _tag);
      return;
    }

    if (_multiDayStressData.isEmpty) {
      developer.log('⚠️ 压力数据缓存为空，跳过上报', name: _tag);
      return;
    }

    _incrementPendingReport();
    try {
      final stressData = <Map<String, dynamic>>[];
      for (var entry in _multiDayStressData.entries) {
        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        stressData.add({
          'list': entry.value,
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
        });
      }

      await DefaultApi().addStressChangeInfoPost<dynamic>(
        deviceSn: deviceSn,
        stress: stressData,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      _markDataAsReported('stressChangeInfo', reportKey);
      _multiDayStressData.clear();
      developer.log('✅ 压力数据上报成功（${stressData.length}天）', name: _tag);
      _updateSyncProgress('压力数据');
    } catch (e) {
      developer.log('❌ 压力数据上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 将 historyDay 字符串转换为日期字符串 (yyyy-MM-dd)
  String _convertHistoryDayToDate(String historyDay) {
    final now = DateTime.now();
    DateTime targetDate;

    if (historyDay == 'TODAY') {
      targetDate = now;
    } else if (historyDay == 'YESTERDAY') {
      targetDate = now.subtract(const Duration(days: 1));
    } else if (historyDay.startsWith('DAYS_AGO_')) {
      final daysAgo =
          int.tryParse(historyDay.substring('DAYS_AGO_'.length)) ?? 0;
      targetDate = now.subtract(Duration(days: daysAgo));
    } else {
      targetDate = now;
    }

    return '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
  }

  /// 批量上报多天运动记录数据
  Future<void> _reportMultiDaySport(String deviceSn) async {
    if (_multiDaySportData.isEmpty) {
      developer.log('⚠️ 没有运动记录数据需要上报', name: _tag);
      return;
    }

    _incrementPendingReport();
    try {
      // 按日期排序（从旧到新）
      final sortedDates = _multiDaySportData.keys.toList()..sort();

      // 构建运动记录列表
      final sportList = sortedDates.map((date) {
        final data = _multiDaySportData[date]!;
        return {
          'dailyValue': data['dailyValue'],
          'steps': data['steps'],
          'distance': data['distance'],
          'calories': data['calories'],
          'sportTime': data['sportTime'],
        };
      }).toList();

      developer.log('📤 批量上报运动记录数据: ${sportList.length}天', name: _tag);

      // 调用批量上报接口
      await DefaultApi().addSportRecordPost<dynamic>(
        sportRecord: RingSportRecord(
          deviceSn: deviceSn,
          steps: 0, // 批量上报时这些字段不使用
          distance: 0,
          calories: 0,
          sportTime: 0,
        ),
        sportList: sportList, // 传递运动记录列表
        isShowErrMsg: false,
        isShowLoading: false,
      );

      developer.log('✅ 运动记录数据批量上报成功', name: _tag);
      _updateSyncProgress('运动记录');

      // 清空缓存
      _multiDaySportData.clear();
    } catch (e) {
      developer.log('❌ 运动记录数据批量上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 单独上报运动记录数据（已废弃，改用批量上报）
  @Deprecated('使用 _reportMultiDaySport 代替')
  Future<void> _autoReportSportRecord(
      String deviceSn, RingSportRecord sportRecord) async {
    // 【修复】移除HRV依赖，直接上报数据
    _incrementPendingReport();
    try {
      final now = DateTime.now();
      final dailyValue =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      // 获取调用堆栈信息（用于调试）
      final stackTrace =
          StackTrace.current.toString().split('\n').take(3).join('\n');
      developer.log('🔍 运动记录上报调用来源:\n$stackTrace', name: _tag);

      // 检查是否已上报
      if (_isDataReported('sportRecord', '$deviceSn:$dailyValue')) {
        developer.log('⚠️ 运动记录数据已上报，跳过重复上报 (steps: ${sportRecord.steps})',
            name: _tag);
        return;
      }

      developer.log('📤 单独上报运动记录数据: $sportRecord', name: _tag);

      await DefaultApi().addSportRecordPost<dynamic>(
        sportRecord: sportRecord,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      // 标记已上报
      _markDataAsReported('sportRecord', '$deviceSn:$dailyValue');
      developer.log('✅ 运动记录数据上报成功', name: _tag);
      _updateSyncProgress('运动记录');
    } catch (e) {
      developer.log('❌ 运动记录数据上报失败: $e', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  /// 单独上报HRV列表数据（收集多天数据）
  Future<void> _autoReportHrvList(String deviceSn, List<int?> hrvList,
      int timeInterval, String historyDay) async {
    try {
      // 缓存 timeInterval
      _cachedTimeInterval = timeInterval;

      // 缓存数据（包括空数据，用于计数）
      _multiDayHrvData[historyDay] = hrvList;
      developer.log(
          '📦 缓存HRV数据: $historyDay (${hrvList.length}条, timeInterval=$timeInterval)',
          name: _tag);

      // 只在收到 DAYS_AGO_7 时触发上报
      if (historyDay == 'DAYS_AGO_7') {
        developer.log('📤 HRV数据收集完成（共${_multiDayHrvData.length}天），开始上报',
            name: _tag);
        await _reportMultiDayHrv(deviceSn, timeInterval);
      }
    } catch (e) {
      developer.log('❌ 缓存HRV数据失败: $e', name: _tag);
    }
  }

  /// 上报多天HRV数据（优先级最高）
  Future<void> _reportMultiDayHrv(String deviceSn, int timeInterval) async {
    developer.log('🚀 【优先上报 1/7】多天HRV列表数据开始上报...', name: _tag);

    final reportKey = '$deviceSn:multiday_hrv';
    if (_isDataReported('hrvInfo', reportKey)) {
      developer.log('⚠️ 多天HRV数据已上报，跳过重复上报', name: _tag);
      _hrvReportCompleted.value = true;
      _processReportQueue();
      return;
    }

    if (_multiDayHrvData.isEmpty) {
      developer.log('⚠️ HRV数据缓存为空，跳过上报', name: _tag);
      _hrvReportCompleted.value = true;
      _processReportQueue();
      return;
    }

    try {
      final hrvData = <Map<String, dynamic>>[];
      for (var entry in _multiDayHrvData.entries) {
        // 过滤掉空数据
        if (entry.value.isEmpty) {
          developer.log('⏭️ 跳过空HRV数据: ${entry.key}', name: _tag);
          continue;
        }

        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        hrvData.add({
          'list': entry.value,
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
          'timeInterval': timeInterval, // 添加 timeInterval 参数
        });
      }

      if (hrvData.isEmpty) {
        developer.log('⚠️ 过滤后没有有效的HRV数据，跳过上报', name: _tag);
        _markDataAsReported('hrvInfo', reportKey);
        _multiDayHrvData.clear();
        _hrvReportCompleted.value = true;
        _processReportQueue();
        return;
      }

      await DefaultApi().addHrvInfoPost<dynamic>(
        deviceSn: deviceSn,
        hrv: hrvData,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      _markDataAsReported('hrvInfo', reportKey);
      _multiDayHrvData.clear();
      developer.log(
          '✅ HRV数据上报成功（${hrvData.length}天有效数据，timeInterval=$timeInterval）',
          name: _tag);

      // 设置进度为 1/7
      _completedSyncSteps.value = 1;
      _syncProgress.value = (1 / _totalSyncSteps.value * 100).round();

      _hrvReportCompleted.value = true;
      _processReportQueue();
    } catch (e) {
      developer.log('❌ HRV数据上报失败: $e', name: _tag);
      _hrvReportCompleted.value = true;
      _processReportQueue();
    }
  }

  /// 解析历史日期字符串为枚举
  CRPHistoryDay _parseHistoryDayString(String historyDayString) {
    switch (historyDayString) {
      case 'TODAY':
        return CRPHistoryDay.TODAY;
      case 'YESTERDAY':
        return CRPHistoryDay.YESTERDAY;
      case 'DAYS_AGO_2':
        return CRPHistoryDay.DAYS_AGO_2;
      case 'DAYS_AGO_3':
        return CRPHistoryDay.DAYS_AGO_3;
      case 'DAYS_AGO_4':
        return CRPHistoryDay.DAYS_AGO_4;
      case 'DAYS_AGO_5':
        return CRPHistoryDay.DAYS_AGO_5;
      case 'DAYS_AGO_6':
        return CRPHistoryDay.DAYS_AGO_6;
      case 'DAYS_AGO_7':
        return CRPHistoryDay.DAYS_AGO_7;
      case 'DAYS_AGO_8':
        return CRPHistoryDay.DAYS_AGO_8;
      case 'DAYS_AGO_9':
        return CRPHistoryDay.DAYS_AGO_9;
      case 'DAYS_AGO_10':
        return CRPHistoryDay.DAYS_AGO_10;
      case 'DAYS_AGO_11':
        return CRPHistoryDay.DAYS_AGO_11;
      case 'DAYS_AGO_12':
        return CRPHistoryDay.DAYS_AGO_12;
      case 'DAYS_AGO_13':
        return CRPHistoryDay.DAYS_AGO_13;
      case 'DAYS_AGO_14':
        return CRPHistoryDay.DAYS_AGO_14;
      default:
        return CRPHistoryDay.TODAY;
    }
  }

  /// 处理待上报队列
  void _processReportQueue() {
    if (_pendingReportQueue.isEmpty) {
      developer.log('📭 待上报队列为空', name: _tag);
      return;
    }

    developer.log('📤 开始处理待上报队列，共${_pendingReportQueue.length}个任务', name: _tag);
    final queue = List<Function>.from(_pendingReportQueue);
    _pendingReportQueue.clear();

    for (final reportFunc in queue) {
      try {
        reportFunc();
      } catch (e) {
        developer.log('❌ 处理队列任务失败: $e', name: _tag);
      }
    }
  }

  // ==================== 扫描和连接相关方法 ====================

  /// 开始扫描戒指设备
  Future<bool> startScan() async {
    try {
      developer.log('🔍 开始扫描戒指设备，清空现有列表 (当前${_scannedDevices.length}个设备)',
          name: _tag);
      _scannedDevices.clear();
      _isScanning.value = true;

      final result = await _methodChannel.invokeMethod<bool>('startScan');
      return result ?? false;
    } catch (e) {
      _isScanning.value = false;
      developer.log('❌ 扫描失败: $e', name: _tag);

      // 处理权限相关错误
      if (e.toString().contains('PERMISSION')) {
        if (e.toString().contains('PERMANENTLY_DENIED')) {
          developer.log('⚠️ 蓝牙权限被永久拒绝，需要手动开启', name: _tag);
          // 可以在这里显示引导用户到设置的提示
        } else {
          developer.log('⚠️ 蓝牙权限不足，请授予权限', name: _tag);
        }
      } else if (e.toString().contains('BLUETOOTH_SCAN')) {
        developer.log('⚠️ 需要蓝牙扫描权限', name: _tag);
      }

      return false;
    }
  }

  /// 停止扫描
  Future<bool> stopScan() async {
    try {
      _isScanning.value = false;
      developer.log('⏹️ 停止扫描', name: _tag);

      final result = await _methodChannel.invokeMethod<bool>('stopScan');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 停止扫描失败: $e', name: _tag);
      return false;
    }
  }

  /// 连接指定设备
  Future<bool> connectDevice(RingDevice device) async {
    try {
      developer.log('🔗 连接设备: ${device.address} (deviceSn: ${device.deviceSn})',
          name: _tag);

      final result = await _methodChannel.invokeMethod<bool>('connectDevice', {
        'address': device.address,
      });

      if (result == true) {
        _connectedDevice.value = device;
        // 保存设备信息到本地存储
        await _deviceStorage.saveConnectedDevice(device);
        developer.log('💾 设备信息已保存到本地存储，deviceSn: ${device.deviceSn}',
            name: _tag);
      }

      return result ?? false;
    } catch (e) {
      developer.log('❌ 连接设备失败: $e', name: _tag);
      return false;
    }
  }

  /// 断开设备连接（保留设备信息以便自动重连）
  Future<bool> disconnectDevice() async {
    try {
      developer.log('🔌 断开设备连接', name: _tag);

      final result =
          await _methodChannel.invokeMethod<bool>('disconnectDevice');

      if (result == true) {
        _connectedDevice.value = null;
        _connectionState.value = RingConnectionState.disconnected;
        _isDeviceBound.value = false; // 重置设备绑定状态
        _isInitializingDevice.value = false; // 重置初始化状态
        _clearReportedDataMarks(); // 清除上报标记

        // 保留设备信息以便自动重连
        developer.log('💾 设备信息已保留，支持自动重连', name: _tag);
      }

      return result ?? false;
    } catch (e) {
      developer.log('❌ 断开连接失败: $e', name: _tag);
      return false;
    }
  }

  /// 解绑设备（断开连接并清除设备信息）
  Future<bool> unbindDevice() async {
    try {
      developer.log('🗑️ 解绑设备', name: _tag);

      // 先断开连接
      final disconnectSuccess = await disconnectDevice();

      if (disconnectSuccess) {
        // 清除本地存储的设备信息
        await _deviceStorage.clearConnectedDevice();
        developer.log('✅ 设备信息已从本地存储清除', name: _tag);
      }

      return disconnectSuccess;
    } catch (e) {
      developer.log('❌ 解绑设备失败: $e', name: _tag);
      return false;
    }
  }

  /// 检查设备连接状态s
  Future<bool> checkConnectionStatus() async {
    try {
      final result = await _methodChannel.invokeMethod<bool>('isConnected');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 检查连接状态失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询步数数据
  Future<bool> queryCurrentSteps() async {
    try {
      print('👟👟👟 [RingService.queryCurrentSteps] 开始调用 Kotlin 查询步数数据');
      developer.log('👟 查询步数数据', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryCurrentSteps');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询步数失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询指定日期的步数数据
  Future<bool> queryStepsForDate(String historyDay) async {
    try {
      developer.log('👟 查询指定日期步数数据: $historyDay', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryStepsForDate', {
        'historyDay': historyDay,
      });
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询指定日期步数失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询睡眠数据
  Future<bool> querySleep() async {
    print('😴😴😴 [RingService.querySleep] 开始调用 Kotlin 查询睡眠数据');
    developer.log('😴 查询睡眠数据', name: _tag);

    try {
      final result = await _methodChannel.invokeMethod('querySleep');
      developer.log('✅ 睡眠数据查询成功: $result', name: _tag);
      return result == true;
    } catch (e) {
      developer.log('❌ 睡眠数据查询失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询心率数据
  Future<bool> queryHeartRate() async {
    try {
      print('❤️❤️❤️ [RingService.queryHeartRate] 开始调用 Kotlin 查询心率数据');
      developer.log('❤️ 查询心率数据', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('queryHeartRate');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询心率数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询电池电量
  Future<bool> queryBattery() async {
    try {
      print('🔋🔋🔋 [RingService.queryBattery] 开始调用 Kotlin 查询电池电量');
      developer.log('🔋 查询电池电量', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('queryBattery');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询电池电量失败: $e', name: _tag);
      return false;
    }
  }

  /// 开始心率测量
  Future<bool> startHeartRateMeasure() async {
    try {
      developer.log('💓 开始心率测量', name: _tag);
      _isHeartRateMeasuring.value = true;
      final result =
          await _methodChannel.invokeMethod<bool>('startHeartRateMeasure');
      if (result != true) {
        _isHeartRateMeasuring.value = false;
      }
      return result ?? false;
    } catch (e) {
      developer.log('❌ 开始心率测量失败: $e', name: _tag);
      _isHeartRateMeasuring.value = false;
      return false;
    }
  }

  /// 停止心率测量
  Future<bool> stopHeartRateMeasure() async {
    try {
      developer.log('⏹️ 停止心率测量', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('stopHeartRateMeasure');
      _isHeartRateMeasuring.value = false;
      return result ?? false;
    } catch (e) {
      developer.log('❌ 停止心率测量失败: $e', name: _tag);
      _isHeartRateMeasuring.value = false;
      return false;
    }
  }

  /// 同步时间
  Future<bool> syncTime() async {
    try {
      developer.log('⏰ 同步时间', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('syncTime');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 同步时间失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询血氧数据
  Future<bool> queryBloodOxygen() async {
    try {
      print('🩸🩸🩸 [RingService.queryBloodOxygen] 开始调用 Kotlin 查询血氧数据');
      developer.log('🩸 查询血氧数据', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryBloodOxygen');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询血氧数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 开始血氧测量
  Future<bool> startBloodOxygenMeasure() async {
    try {
      developer.log('🩸 开始血氧测量', name: _tag);
      _isBloodOxygenMeasuring.value = true;
      final result =
          await _methodChannel.invokeMethod<bool>('startBloodOxygenMeasure');
      if (result != true) {
        _isBloodOxygenMeasuring.value = false;
      }
      return result ?? false;
    } catch (e) {
      developer.log('❌ 开始血氧测量失败: $e', name: _tag);
      _isBloodOxygenMeasuring.value = false;
      return false;
    }
  }

  /// 停止血氧测量
  Future<bool> stopBloodOxygenMeasure() async {
    try {
      developer.log('⏹️ 停止血氧测量', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('stopBloodOxygenMeasure');
      _isBloodOxygenMeasuring.value = false;
      return result ?? false;
    } catch (e) {
      developer.log('❌ 停止血氧测量失败: $e', name: _tag);
      _isBloodOxygenMeasuring.value = false;
      return false;
    }
  }

  /// 查询指定日期的血氧数据
  Future<bool> queryBloodOxygenForDate(String historyDay) async {
    try {
      developer.log('🩸 查询指定日期血氧数据: $historyDay', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryBloodOxygenForDate', {
        'historyDay': historyDay,
      });
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询指定日期血氧数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询HRV数据
  Future<bool> queryHrv() async {
    try {
      print('🫀🫀🫀 [RingService.queryHrv] 开始调用 Kotlin 查询HRV数据');
      developer.log('🫀 查询HRV数据', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('queryHrv');
      print('🫀 [RingService.queryHrv] Kotlin 返回结果: $result');
      developer.log('🫀 Kotlin返回HRV查询结果: $result', name: _tag);
      return result ?? false;
    } catch (e, stackTrace) {
      print('❌ [RingService.queryHrv] 查询HRV数据异常: $e');
      print('❌ [RingService.queryHrv] 堆栈: $stackTrace');
      developer.log('❌ 查询HRV数据失败: $e\n堆栈: $stackTrace', name: _tag);
      return false;
    }
  }

  /// 开始HRV测量
  Future<bool> startHrvMeasure() async {
    try {
      developer.log('🫀 开始HRV测量', name: _tag);
      _isHrvMeasuring.value = true;
      final result = await _methodChannel.invokeMethod<bool>('startHrvMeasure');
      if (result != true) {
        _isHrvMeasuring.value = false;
      }
      return result ?? false;
    } catch (e) {
      developer.log('❌ 开始HRV测量失败: $e', name: _tag);
      _isHrvMeasuring.value = false;
      return false;
    }
  }

  /// 停止HRV测量
  Future<bool> stopHrvMeasure() async {
    try {
      developer.log('⏹️ 停止HRV测量', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('stopHrvMeasure');
      _isHrvMeasuring.value = false;
      return result ?? false;
    } catch (e) {
      developer.log('❌ 停止HRV测量失败: $e', name: _tag);
      _isHrvMeasuring.value = false;
      return false;
    }
  }

  /// 查询压力数据
  Future<bool> queryStress() async {
    try {
      developer.log('😰 查询压力数据', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('queryStress');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询压力数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询今日压力列表数据
  Future<bool> queryTodayStressList() async {
    try {
      print('😰😰😰 [RingService.queryTodayStressList] 开始调用 Kotlin 查询压力列表数据');
      developer.log('📊 查询今日压力列表数据', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryTodayStressList');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询今日压力列表数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 开始压力测量
  Future<bool> startStressMeasure() async {
    try {
      developer.log('😰 开始压力测量', name: _tag);
      _isStressMeasuring.value = true;
      final result =
          await _methodChannel.invokeMethod<bool>('startStressMeasure');
      if (result != true) {
        _isStressMeasuring.value = false;
      }
      return result ?? false;
    } catch (e) {
      developer.log('❌ 开始压力测量失败: $e', name: _tag);
      _isStressMeasuring.value = false;
      return false;
    }
  }

  /// 停止压力测量
  Future<bool> stopStressMeasure() async {
    try {
      developer.log('⏹️ 停止压力测量', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('stopStressMeasure');
      _isStressMeasuring.value = false;
      return result ?? false;
    } catch (e) {
      developer.log('❌ 停止压力测量失败: $e', name: _tag);
      _isStressMeasuring.value = false;
      return false;
    }
  }

  /// 发送用户信息
  Future<bool> sendUserInfo({
    required int weight,
    required int height,
    required int gender,
    required int age,
    required int stride,
  }) async {
    try {
      developer.log('👤 发送用户信息', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('sendUserInfo', {
        'weight': weight,
        'height': height,
        'gender': gender,
        'age': age,
        'stride': stride,
      });
      return result ?? false;
    } catch (e) {
      developer.log('❌ 发送用户信息失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询锻炼详情
  Future<bool> queryExerciseDetails() async {
    try {
      print('🏃🏃🏃 [RingService.queryExerciseDetails] 开始调用 Kotlin 查询锻炼详情');
      developer.log('🏃 查询锻炼详情', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryExerciseDetails');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询锻炼详情失败: $e', name: _tag);
      return false;
    }
  }

  // ==================== 训练相关方法 ====================

  /// 查询支持的训练类型
  Future<bool> querySupportTraining() async {
    try {
      developer.log('🏃 查询支持的训练类型', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('querySupportTraining');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询支持的训练类型失败: $e', name: _tag);
      return false;
    }
  }

  /// 开始训练
  Future<bool> startTraining({
    required String type,
    int? caloriesGoal,
    int? durationGoal,
    int? distanceGoal,
  }) async {
    try {
      developer.log('🏃 开始训练: type=$type', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('startTraining', {
        'type': type,
        'caloriesGoal': caloriesGoal,
        'durationGoal': durationGoal,
        'distanceGoal': distanceGoal,
      });
      return result ?? false;
    } catch (e) {
      developer.log('❌ 开始训练失败: $e', name: _tag);
      return false;
    }
  }

  /// 暂停训练
  Future<bool> pauseTraining() async {
    try {
      developer.log('⏸️ 暂停训练', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('pauseTraining');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 暂停训练失败: $e', name: _tag);
      return false;
    }
  }

  /// 继续训练
  Future<bool> resumeTraining() async {
    try {
      developer.log('▶️ 继续训练', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('resumeTraining');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 继续训练失败: $e', name: _tag);
      return false;
    }
  }

  /// 结束训练
  Future<bool> endTraining() async {
    try {
      developer.log('⏹️ 结束训练', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>('endTraining');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 结束训练失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询当前训练状态
  Future<bool> queryTrainingState() async {
    try {
      developer.log('🏃 查询当前训练状态', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryTrainingState');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询训练状态失败: $e', name: _tag);
      return false;
    }
  }

  /// 查询历史训练数据（从SDK获取）
  Future<bool> queryHistoryTraining() async {
    try {
      developer.log('🏃 查询历史训练数据', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('queryHistoryTraining');
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询历史训练数据失败: $e', name: _tag);
      return false;
    }
  }

  /// 根据ID查询训练详情
  Future<bool> queryTrainingById(int id) async {
    try {
      developer.log('🏃 查询训练详情: id=$id', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>(
        'queryTrainingById',
        {'id': id},
      );
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询训练详情失败: $e', name: _tag);
      return false;
    }
  }

  /// 根据索引查询特定训练的详情（旧方法，保留兼容性）
  Future<bool> queryTrainingByIndex(int index) async {
    try {
      developer.log('🏃 查询训练详情: index=$index', name: _tag);
      final result = await _methodChannel.invokeMethod<bool>(
        'queryTrainingByIndex',
        {'index': index},
      );
      return result ?? false;
    } catch (e) {
      developer.log('❌ 查询训练详情失败: $e', name: _tag);
      return false;
    }
  }

  /// 获取所有戒指数据（手动调用Android端fetchAllDeviceData方法）
  Future<bool> fetchAllDeviceData() async {
    try {
      developer.log('📊 手动调用获取所有设备数据', name: _tag);
      final result =
          await _methodChannel.invokeMethod<bool>('fetchAllDeviceData');
      if (result == true) {
        developer.log('✅ 所有设备数据获取成功', name: _tag);
      } else {
        developer.log('❌ 所有设备数据获取失败', name: _tag);
      }
      return result ?? false;
    } catch (e) {
      developer.log('❌ 调用fetchAllDeviceData失败: $e', name: _tag);
      return false;
    }
  }

  /// 获取所有戒指数据
  Future<void> fetchAllData() async {
    if (!isConnected) {
      developer.log('⚠️ 设备未连接，无法获取数据', name: _tag);
      return;
    }

    developer.log('📊 开始获取所有戒指数据', name: _tag);

    await Future.wait([
      queryCurrentSteps(),
      // querySleep(),
      // queryHeartRate(),
      queryBattery(),
      // queryBloodOxygen(),
      // queryHrv(),
      // queryStress(),
    ]);
  }

  /// 自动重连功能
  Future<bool> autoReconnect() async {
    try {
      // 检查是否有存储的设备信息
      if (!_deviceStorage.hasStoredDevice()) {
        developer.log('⚠️ 没有可自动重连的设备信息', name: _tag);
        return false;
      }

      // 检查是否已经连接
      if (isConnected) {
        developer.log('✅ 设备已连接，无需重连', name: _tag);
        return true;
      }

      final storedDevice = _deviceStorage.lastConnectedDevice;
      if (storedDevice == null) {
        developer.log('⚠️ 存储的设备信息为空', name: _tag);
        return false;
      }

      developer.log(
          '🔄 开始自动重连设备: ${storedDevice.name} (${storedDevice.address})',
          name: _tag);

      // 尝试连接存储的设备
      final success = await connectDevice(storedDevice);

      if (success) {
        developer.log('✅ 自动重连成功', name: _tag);
      } else {
        developer.log('❌ 自动重连失败', name: _tag);
      }

      return success;
    } catch (e) {
      developer.log('❌ 自动重连异常: $e', name: _tag);
      return false;
    }
  }

  /// 检查并尝试自动重连
  Future<void> checkAndAutoReconnect() async {
    try {
      // 延迟一点时间，确保应用完全启动
      await Future.delayed(const Duration(seconds: 2));

      // 检查当前连接状态
      if (isConnected) {
        developer.log('✅ 设备已连接，自动刷新数据', name: _tag);
        // 如果已连接，自动刷新数据
        await fetchAllData();
      } else {
        // 检查是否有存储的设备信息，但不打印加载信息
        try {
          if (_deviceStorage.hasStoredDevice()) {
            developer.log('🔍 检测到存储的设备，尝试自动重连', name: _tag);
            await autoReconnect();
          } else {
            developer.log('ℹ️ 没有存储的设备信息，无需自动重连', name: _tag);
          }
        } catch (e) {
          developer.log('⚠️ 检查存储设备信息失败: $e', name: _tag);
          // 如果检查存储设备信息失败，不进行重连
        }
      }
    } catch (e) {
      developer.log('❌ 检查自动重连失败: $e', name: _tag);
    }
  }

  /// 绑定设备到服务器
  ///
  /// [deviceSn] 设备序列号
  /// 返回绑定是否成功
  Future<bool> _bindDevice(String deviceSn) async {
    try {
      developer.log('� 开始绑定 设备到服务器: $deviceSn', name: _tag);

      if (deviceSn.isEmpty) {
        developer.log('❌ 设备序列号为空，无法绑定', name: _tag);
        return false;
      }

      // 调用addDevicePost接口绑定设备
      final response = await DefaultApi().addDevicePost<Map<String, dynamic>>(
        deviceSn: deviceSn,
        isShowErrMsg: false, // 不显示错误消息，避免干扰用户
        isShowLoading: false, // 不显示加载状态
      );

      if (response != null) {
        _isDeviceBound.value = true;
        developer.log('✅ 设备绑定成功: $deviceSn, 响应: $response', name: _tag);
        return true;
      } else {
        developer.log('⚠️ 设备绑定响应为空: $deviceSn', name: _tag);
        return false;
      }
    } catch (e) {
      developer.log('❌ 设备绑定失败: $deviceSn, 错误: $e', name: _tag);
      return false;
    }
  }

  /// 获取当前连接设备的 deviceSn
  ///
  /// 返回当前连接设备的序列号，如果未连接则返回空字符串
  String getCurrentDeviceSn() {
    final device = _connectedDevice.value;
    if (device != null) {
      developer.log('📱 当前设备 deviceSn: ${device.deviceSn}', name: _tag);
      return device.deviceSn;
    }
    developer.log('⚠️ 当前没有连接的设备', name: _tag);
    return '';
  }

  /// 返回当前连接设备的完整信息，包括 deviceSn
  RingDevice? getCurrentDevice() {
    return _connectedDevice.value;
  }

  /// 手动绑定当前连接的设备
  ///
  /// 返回绑定是否成功
  Future<bool> bindCurrentDevice() async {
    final deviceSn = getCurrentDeviceSn();
    if (deviceSn.isEmpty) {
      developer.log('❌ 没有连接的设备，无法绑定', name: _tag);
      return false;
    }

    return await _bindDevice(deviceSn);
  }

  /// 检查当前设备是否已绑定
  ///
  /// 返回设备是否已绑定到服务器
  bool isCurrentDeviceBound() {
    return _isDeviceBound.value && getCurrentDeviceSn().isNotEmpty;
  }

  /// 处理历史心率数据接收事件
  void _handleHistoryHeartRateReceived(dynamic arguments) {
    Map<String, dynamic>? heartRateMap;

    if (arguments is Map<String, dynamic>) {
      heartRateMap = arguments;
    } else if (arguments is Map) {
      heartRateMap = Map<String, dynamic>.from(arguments);
    }

    if (heartRateMap != null) {
      try {
        final historyHeartRateData = HistoryHeartRateData.fromMap(heartRateMap);
        _historyHeartRateData.value = historyHeartRateData;

        // 立即上报历史心率数据
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isNotEmpty &&
            historyHeartRateData.heartRateList.isNotEmpty) {
          _autoReportHistoryHeartRate(deviceSn, historyHeartRateData);
        }
      } catch (e) {
        developer.log('❌ 解析历史心率数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理锻炼详情接收事件
  void _handleExerciseDetailsReceived(dynamic arguments) {
    developer.log('🏃 收到锻炼详情数据: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null) {
      try {
        // 更新锻炼详情数据
        _exerciseDetail.value = dataMap;
        developer.log('✅ 锻炼详情数据已更新', name: _tag);

        // 获取设备序列号
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isEmpty) {
          developer.log('❌ 设备未连接，无法解析运动记录', name: _tag);
          return;
        }

        // 解析运动记录数据
        final sportRecord = RingSportRecord(
          deviceSn: deviceSn,
          steps: dataMap['steps'] ?? 0,
          distance: dataMap['distance'] ?? 0,
          calories: dataMap['calories'] ?? 0,
          sportTime: dataMap['sportTime'] ?? 0,
        );

        _sportRecord.value = sportRecord;
        developer.log('✅ 运动记录数据更新: $sportRecord', name: _tag);

        // 立即上报运动记录数据
        if (sportRecord.steps > 0) {
          _autoReportSportRecord(deviceSn, sportRecord);
        }
      } catch (e) {
        developer.log('❌ 解析运动记录数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理每日锻炼详情接收事件
  void _handleDailyExerciseDetailsReceived(dynamic arguments) {
    developer.log('📊 收到每日锻炼详情数据: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null) {
      try {
        // 获取设备序列号
        final deviceSn = getCurrentDeviceSn();
        if (deviceSn.isEmpty) {
          developer.log('❌ 设备未连接，无法解析每日运动记录', name: _tag);
          return;
        }

        // 解析运动记录数据
        final sportRecord = RingSportRecord(
          deviceSn: deviceSn,
          steps: dataMap['steps'] ?? 0,
          distance: dataMap['distance'] ?? 0,
          calories: dataMap['calories'] ?? 0,
          sportTime: dataMap['sportTime'] ?? 0,
        );

        _sportRecord.value = sportRecord;
        developer.log('✅ 每日运动记录数据更新: $sportRecord', name: _tag);

        // 立即上报运动记录数据
        if (sportRecord.steps > 0) {
          _autoReportSportRecord(deviceSn, sportRecord);
        }
      } catch (e) {
        developer.log('❌ 解析每日运动记录数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理训练数据接收事件（单个训练的详细数据）
  void _handleTrainingDataReceived(dynamic arguments) {
    developer.log('🏃 收到训练详细数据: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null) {
      try {
        // 更新锻炼详情数据，触发监听器
        _exerciseDetail.value = dataMap;
        developer.log('✅ 训练详细数据已更新，触发监听器', name: _tag);
      } catch (e) {
        developer.log('❌ 处理训练详细数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理历史训练数据接收事件
  void _handleHistoryTrainingReceived(dynamic arguments) {
    developer.log('🏃 收到历史训练数据: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null) {
      try {
        // 处理新版SDK返回的historyList格式
        if (dataMap.containsKey('historyList')) {
          final historyList = dataMap['historyList'];
          if (historyList is List) {
            final trainingList = historyList.map((item) {
              if (item is Map) {
                return Map<String, dynamic>.from(item);
              }
              return <String, dynamic>{'rawData': item.toString()};
            }).toList();

            _historyTrainingList.value = trainingList;
            developer.log('✅ 历史训练数据更新: ${trainingList.length} 条记录', name: _tag);
          }
        }
        // 兼容旧版格式
        else if (dataMap.containsKey('data')) {
          final data = dataMap['data'];
          if (data is List) {
            final trainingList = data.map((item) {
              if (item is Map) {
                return Map<String, dynamic>.from(item);
              }
              return <String, dynamic>{'rawData': item.toString()};
            }).toList();

            _historyTrainingList.value = trainingList;
            developer.log('✅ 历史训练数据更新: ${trainingList.length} 条记录', name: _tag);
          }
        }
      } catch (e) {
        developer.log('❌ 解析历史训练数据失败: $e', name: _tag);
      }
    }
  }

  /// 处理支持的训练类型列表
  void _handleSupportTrainingListReceived(dynamic arguments) {
    developer.log('🏃 收到支持的训练类型列表: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('trainingTypes')) {
      try {
        final types = dataMap['trainingTypes'];
        if (types is List) {
          _supportedTrainingTypes.value =
              types.map((e) => e.toString()).toList();
          developer.log('✅ 支持的训练类型: $_supportedTrainingTypes', name: _tag);
        }
      } catch (e) {
        developer.log('❌ 解析训练类型列表失败: $e', name: _tag);
      }
    }
  }

  /// 处理训练状态变化
  void _handleTrainingStateChanged(dynamic arguments) {
    developer.log('🏃 训练状态变化: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('state')) {
      try {
        final state = dataMap['state'].toString();
        _trainingState.value = state;
        developer.log('✅ 训练状态更新: $state', name: _tag);
      } catch (e) {
        developer.log('❌ 解析训练状态失败: $e', name: _tag);
      }
    }
  }

  /// 处理训练详情数据
  void _handleTrainingDetailsReceived(dynamic arguments) {
    developer.log('🏃 收到训练详情: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null) {
      try {
        _trainingDetails.value = dataMap;
        developer.log('✅ 训练详情更新: $dataMap', name: _tag);
      } catch (e) {
        developer.log('❌ 解析训练详情失败: $e', name: _tag);
      }
    }
  }

  /// 处理训练目标达成
  void _handleTrainingGoalReached(dynamic arguments) {
    developer.log('🎯 训练目标达成: $arguments', name: _tag);

    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap != null && dataMap.containsKey('goalType')) {
      try {
        final goalType = dataMap['goalType'].toString();
        developer.log('🎯 达成目标类型: $goalType', name: _tag);
        // 可以在这里触发通知或UI更新
      } catch (e) {
        developer.log('❌ 解析目标类型失败: $e', name: _tag);
      }
    }
  }

  /// 处理活动详情接收事件（收集多天数据）
  Future<void> _handleActionDetailsReceived(dynamic arguments) async {
    Map<String, dynamic>? dataMap;
    if (arguments is Map<String, dynamic>) {
      dataMap = arguments;
    } else if (arguments is Map) {
      dataMap = Map<String, dynamic>.from(arguments);
    }

    if (dataMap == null) {
      developer.log('❌ 活动详情数据为空', name: _tag);
      return;
    }

    try {
      // 从rawData中提取数据
      final rawData = dataMap['rawData'];
      if (rawData == null) {
        developer.log('❌ rawData为空', name: _tag);
        return;
      }

      // 解析rawData字符串，提取historyDay和actionList
      String? historyDay;
      List<int>? actionList;

      if (rawData is String) {
        final historyDayMatch = RegExp(r'historyDay=(\w+)').firstMatch(rawData);
        historyDay = historyDayMatch?.group(1);

        final actionListMatch =
            RegExp(r'actionList=\[([\d,\s]+)\]').firstMatch(rawData);
        if (actionListMatch != null) {
          final actionListStr = actionListMatch.group(1);
          if (actionListStr != null) {
            actionList = actionListStr
                .split(',')
                .map((s) => int.tryParse(s.trim()) ?? 0)
                .toList();
          }
        } else {
          // actionList为空的情况（actionList=[]）
          actionList = [];
        }
      }

      if (historyDay == null) {
        developer.log('❌ 无法解析活动详情数据', name: _tag);
        return;
      }

      // 【修复】只缓存有数据的天数，空数据不缓存
      if (actionList != null && actionList.isNotEmpty) {
        _multiDayEventData[historyDay] = actionList;
        developer.log('📦 缓存活动详情数据: $historyDay, 数据量: ${actionList.length}',
            name: _tag);
      } else {
        developer.log('⚠️ 跳过空的活动详情数据: $historyDay', name: _tag);
      }

      // 【修复】收到最后一天的数据（DAYS_AGO_7）后，无论是否收集齐8天，都立即上报
      // 或者已经收集到足够的数据（至少有一天有数据）
      if (historyDay == 'DAYS_AGO_7' || _multiDayEventData.length >= 8) {
        if (_multiDayEventData.isNotEmpty) {
          developer.log('📤 触发活动详情数据上报（已收集${_multiDayEventData.length}天有效数据）',
              name: _tag);
          await _reportMultiDayEvent();
        } else {
          developer.log('⚠️ 没有有效的活动详情数据，跳过上报', name: _tag);
          // 即使没有数据也要结束同步状态
          _isDataSyncing.value = false;
          developer.log('🎉 数据同步完成（无活动详情数据）', name: _tag);
        }
      }
    } catch (e) {
      developer.log('❌ 缓存活动详情数据失败: $e', name: _tag);
    }
  }

  /// 上报多天活动详情数据
  Future<void> _reportMultiDayEvent() async {
    try {
      final deviceSn = getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备未连接，无法上报活动详情', name: _tag);
        return;
      }

      final reportKey = '$deviceSn:multiday_event';
      if (_isDataReported('eventInfo', reportKey)) {
        developer.log('⚠️ 多天活动详情数据已上报，跳过重复上报', name: _tag);
        return;
      }

      developer.log('📤 上报多天活动详情数据: ${_multiDayEventData.length}天', name: _tag);

      // 构建多天数据（转换为 API 期望的格式）
      final eventData = <Map<String, dynamic>>[];
      for (var entry in _multiDayEventData.entries) {
        final historyDayEnum = _parseHistoryDayString(entry.key);
        final dailyValue = HistoryDayHelper.getDailyValue(historyDayEnum);

        eventData.add({
          'list': entry.value,
          'dailyValue': dailyValue,
          'historyDay': dailyValue, // 使用和 dailyValue 相同的值
        });
      }

      // 批量上报所有天的数据
      await DefaultApi().addEventInfoPost<dynamic>(
        deviceSn: deviceSn,
        event: eventData,
        isShowLoading: false,
        isShowErrMsg: false,
      );

      _markDataAsReported('eventInfo', reportKey);
      _multiDayEventData.clear();
      developer.log('✅ 多天活动详情数据上报成功', name: _tag);
      _updateSyncProgress('活动详情');

      // 所有关键数据上报完成，结束数据同步状态
      _isDataSyncing.value = false;
      developer.log('🎉 数据同步完全完成，进度条隐藏', name: _tag);

      final statusLogic = Get.find<StatusLogic>();
      statusLogic.refreshCardData();

      // 生成今日签并自动分享
      try {
        final todaySignResult =
            await DefaultApi().addTodaySignPost<Map<String, dynamic>>(
          deviceSn: deviceSn,
          isShowLoading: false,
        );

        // 如果生成今日签成功，自动分享
        if (todaySignResult != null && todaySignResult['code'] == 200) {
          try {
            await DefaultApi().addAutomaticShareSignPost(
              deviceSn: deviceSn,
              isShowLoading: false,
            );
          } catch (shareError) {
            developer.log('自动分享今日签失败: $shareError', name: _tag);
          }
        } else {
          developer.log('⚠️ 今日签生成失败或返回数据异常', name: _tag);
        }
      } catch (e) {
        developer.log('❌ 生成今日签失败: $e', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 上报多天活动详情失败: $e', name: _tag);
      _isDataSyncing.value = false;
    }
  }

  Future<void> _handleReportSleepDetailData(Map<String, dynamic> data) async {
    _incrementPendingReport();
    try {
      // 使用当前设备的deviceSn
      final currentDeviceSn = getCurrentDeviceSn();
      if (currentDeviceSn.isEmpty) {
        developer.log('❌ 设备未连接，无法上报睡眠详情数据', name: _tag);
        return;
      }

      // 检查是否是重复的睡眠数据（根据结束时间判断）
      final endDate = data['endDate'] ?? '';
      if (_lastReportedSleepEndTime != null &&
          _lastReportedSleepEndTime == endDate &&
          endDate.isNotEmpty) {
        developer.log('⚠️ 睡眠数据已上报过，跳过重复上报。endDate: $endDate', name: _tag);
        return;
      }

      developer.log('📊 使用设备SN: $currentDeviceSn', name: _tag);

      // 创建睡眠详情对象
      developer.log('📤 准备调用addSleepDetailPost API', name: _tag);

      // 安全的类型转换函数
      int _toInt(dynamic value, int defaultValue) {
        if (value == null) return defaultValue;
        if (value is int) return value;
        if (value is double) return value.toInt();
        if (value is String) return int.tryParse(value) ?? defaultValue;
        return defaultValue;
      }

      double _toDouble(dynamic value, double defaultValue) {
        if (value == null) return defaultValue;
        if (value is double) return value;
        if (value is int) return value.toDouble();
        if (value is String) return double.tryParse(value) ?? defaultValue;
        return defaultValue;
      }

      final sleepDetail = SleepDetail(
        id: data['id'] != null ? _toInt(data['id'], 0) : null,
        type: data['type']?.toString(),
        score: data['score'] != null ? _toInt(data['score'], 0) : null,
        deviceSn: currentDeviceSn, // 使用当前设备的deviceSn
        startDate: data['startDate']?.toString() ?? '',
        endDate: data['endDate']?.toString() ?? '',
        sleepTime: _toInt(data['sleepTime'], 0),
        sleepEfficiency: _toDouble(data['sleepEfficiency'], 0.0),
        dailyValue: data['dailyValue']?.toString() ?? '',
        deepTime: _toInt(data['deepTime'], 0),
        lightTime: _toInt(data['lightTime'], 0),
        awakeTime: _toInt(data['awakeTime'], 0),
        remTime: _toInt(data['remTime'], 0),
        rawBytes: (data['rawBytes'] as List<dynamic>?)?.map((e) {
              if (e is int) {
                return e;
              } else if (e is double) {
                return e.toInt();
              } else {
                return 0;
              }
            }).toList() ??
            [],
        totalTime: _toInt(data['totalTime'], 0),
        state: data['state']?.toString() ?? 'COLLECTING',
        sleepChronotype: data['sleepChronotype']?.toString() ?? '',
        highConfidence: data['highConfidence']?.toString() ?? 'false',
        bedtime: _toInt(data['bedtime'], 0),
        details: (data['details'] as List<dynamic>?)?.map((item) {
              // 安全的类型转换
              Map<String, dynamic> detailMap;
              if (item is Map<String, dynamic>) {
                detailMap = item;
              } else if (item is Map) {
                detailMap = Map<String, dynamic>.from(item);
              } else {
                developer.log('❌ 无效的detail类型: ${item.runtimeType}', name: _tag);
                return SleepDetailItem(
                  type: 0,
                  startTime: 0,
                  endTime: 0,
                  totalTime: 0,
                );
              }

              return SleepDetailItem(
                type: _toInt(detailMap['type'], 0),
                startTime: _toInt(detailMap['startTime'], 0),
                endTime: _toInt(detailMap['endTime'], 0),
                totalTime: _toInt(detailMap['totalTime'], 0),
              );
            }).toList() ??
            [],
      );

      // 调用API上报睡眠详情睡眠结束时间相同，跳过重复上报
      final response = await DefaultApi().addSleepDetailPost<dynamic>(
        sleepDetail: sleepDetail,
        historyDay: data['dailyValue'],
      );

      _lastReportedSleepEndTime = sleepDetail.endDate;

      developer.log('✅ 睡眠详情数据上报成功，响应: $response', name: _tag);
    } catch (e) {
      developer.log('❌ 睡眠详情数据上报失败: $e', name: _tag);
      developer.log('❌ 错误堆栈: ${e.toString()}', name: _tag);
    } finally {
      _decrementPendingReport();
    }
  }

  @override
  void onClose() {
    disconnectDevice();
    _isDeviceBound.value = false; // 重置设备绑定状态
    _isInitializingDevice.value = false; // 重置初始化状态
    super.onClose();
  }

  /// ==================== 锻炼记录相关方法 ====================

  /// 查询锻炼列表（二级页）
  Future<List<Map<String, dynamic>>> queryExerciseList({
    required String deviceSn,
    required String recordDate,
    String type = '1',
  }) async {
    try {
      final result = await DefaultApi().queryExerciseListGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: type,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (result != null && result is Map) {
        final data = result['data'];
        if (data is List) {
          return List<Map<String, dynamic>>.from(data);
        }
      }
      return [];
    } catch (e) {
      print('❌ 查询锻炼列表失败: $e');
      return [];
    }
  }

  /// 查询锻炼详情（三级页）
  Future<Map<String, dynamic>?> queryExerciseDetail(String id) async {
    try {
      print('📊 开始查询锻炼详情: $id');
      final result = await DefaultApi().queryExerciseDetailGet(
        id: id,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (result != null && result is Map) {
        return result['data'] as Map<String, dynamic>?;
      }
      return null;
    } catch (e) {
      print('❌ 查询锻炼详情失败: $e');
      return null;
    }
  }

  /// 查询锻炼平均心率（三级页）
  Future<Map<String, dynamic>?> queryExerciseHeartRate(String id) async {
    try {
      print('📊 开始查询锻炼平均心率: $id');
      final result = await DefaultApi().queryExerciseHeartRateGet(
        id: id,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (result != null && result is Map) {
        return result['data'] as Map<String, dynamic>?;
      }
      return null;
    } catch (e) {
      print('❌ 查询锻炼平均心率失败: $e');
      return null;
    }
  }

  /// 查询锻炼心率区间（三级页）
  Future<Map<String, dynamic>?> queryExerciseInterval(String id) async {
    try {
      print('📊 开始查询锻炼心率区间: $id');
      final result = await DefaultApi().queryExerciseIntervalGet(
        id: id,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (result != null && result is Map) {
        return result['data'] as Map<String, dynamic>?;
      }
      return null;
    } catch (e) {
      print('❌ 查询锻炼心率区间失败: $e');
      return null;
    }
  }

  /// 查询锻炼步频步长（三级页）
  Future<Map<String, dynamic>?> queryExerciseCadenceInfo(String id) async {
    try {
      print('📊 开始查询锻炼步频步长: $id');
      final result = await DefaultApi().queryExerciseCadenceInfoGet(
        id: id,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (result != null && result is Map) {
        return result['data'] as Map<String, dynamic>?;
      }
      return null;
    } catch (e) {
      print('❌ 查询锻炼步频步长失败: $e');
      return null;
    }
  }

  /// 解析SDK返回的锻炼详情数据
  Map<String, dynamic> parseTrainingInfo(Map<String, dynamic> rawData) {
    try {
      // 修正时间戳（SDK返回的时间戳可能有问题，需要除以1000）
      final rawStartTime = rawData['rawStartTime'] as int? ?? 0;
      final startTime = rawData['startTime'] as int? ?? 0;
      final endTime = rawData['endTime'] as int? ?? 0;

      // 将毫秒时间戳转换为DateTime
      final startDateTime = DateTime.fromMillisecondsSinceEpoch(startTime);
      final endDateTime = DateTime.fromMillisecondsSinceEpoch(endTime);

      // 计算实际时长（秒）
      final validTime = rawData['validTime'] as int? ?? 0;

      // 获取心率列表
      final hrList = rawData['hrList'] as List? ?? [];
      final heartRateList = hrList.map((hr) => hr as int? ?? 0).toList();

      // 计算平均心率（排除0值）
      final validHeartRates = heartRateList.where((hr) => hr > 0).toList();
      final averageHeartRate = validHeartRates.isNotEmpty
          ? (validHeartRates.reduce((a, b) => a + b) / validHeartRates.length)
              .round()
          : 0;

      return {
        'exerciseType': rawData['type'] ?? 0,
        'startDate': startDateTime.toString(),
        'endDate': endDateTime.toString(),
        'exerciseTime': validTime,
        'exerciseCalorie': rawData['calories'] ?? 0,
        'steps': rawData['steps'] ?? 0,
        'distance': rawData['distance'] ?? 0,
        'heartRateList': heartRateList,
        'averageHeartRate': averageHeartRate,
        'goalType': rawData['goalType'] ?? 255,
        'goalValue': rawData['goalValue'] ?? 0,
      };
    } catch (e) {
      print('❌ 解析锻炼详情失败: $e');
      return {};
    }
  }
}
